StellaOps.Microservice

Microservice SDK for the Router: registers the endpoints of a service, connects it to a gateway over a Router transport and dispatches the requests it receives.

library
Component
Router
Licence
Apache-2.0
Target framework
net10.0
Latest release
1.0.1-20261117T070237Z

Install

dotnet add package StellaOps.Microservice --version 1.0.1-20261117T070237Z

Namespaces

NamespaceTypes
StellaOps.Microservice39
StellaOps.Microservice.Endpoints4
StellaOps.Microservice.Streaming3
StellaOps.Microservice.Validation10

namespace StellaOps.Microservice

TypeKindDescription
ClaimRequirementConfigclassConfiguration for a claim requirement.
EndpointDiscoveryServiceclassService that discovers endpoints and applies YAML configuration overrides.
EndpointMatchclassRepresents a matched endpoint with extracted path parameters.
EndpointOverrideConfigclassConfiguration for overriding an endpoint’s properties.
EndpointOverrideMergerclassMerges endpoint overrides from YAML configuration with code defaults.
EndpointRegistryclassDefault implementation of endpoint registry using path matchers.
GeneratedEndpointDiscoveryProviderclassDiscovers endpoints using source-generated provider, falling back to reflection.
HeaderCollectionclassDefault implementation of header collection.
IEndpointDiscoveryProviderinterfaceProvides endpoint discovery functionality.
IEndpointDiscoveryServiceinterfaceInterface for discovering endpoints with YAML configuration support.
IEndpointOverrideMergerinterfaceInterface for merging endpoint overrides from YAML configuration.
IEndpointRegistryinterfaceRegistry for looking up endpoint handlers by method and path.
IEndpointSchemaDefinitionProviderinterfaceOptional provider for endpoint JSON schema definitions discovered at runtime.
IGeneratedEndpointProviderinterfaceInterface implemented by the source-generated endpoint provider.
IHeaderCollectioninterfaceAbstraction for HTTP-style header collection.
IMicroserviceYamlLoaderinterfaceInterface for loading microservice YAML configuration.
IRawStellaEndpointinterfaceInterface for a raw Stella endpoint that handles requests with full context.
IRequestDispatcherinterfaceAbstraction for dispatching Router request frames to handlers.
IRouterConnectionManagerinterfaceManages connections to router gateways.
IStellaEndpointinterfaceMarker interface for all Stella endpoints.
IStellaEndpoint<TRequest, TResponse>interfaceInterface for a typed Stella endpoint with request and response.
IStellaEndpoint<TResponse>interfaceInterface for a typed Stella endpoint with response only (no request body).
InflightRequestTrackerclassTracks in-flight requests and manages their cancellation tokens.
MicroserviceHostedServiceclassHosted service that manages the microservice lifecycle.
MicroserviceServiceCollectionExtensionsclassExtension methods for registering Stella microservice services.
MicroserviceYamlConfigclassRoot configuration for microservice endpoint overrides loaded from YAML.
MicroserviceYamlLoaderclassLoads microservice configuration from a YAML file.
RawRequestContextclassContext for a raw request.
RawResponseclassRepresents a raw response from an endpoint.
ReflectionEndpointDiscoveryProviderclassDiscovers endpoints using runtime reflection.
RequestDispatcherclassDispatches incoming REQUEST frames to the appropriate endpoint handlers.
RouterConnectionManagerclassManages connections to router gateways.
RouterEndpointConfigclassConfiguration for a router endpoint.
SchemaProviderDiscoveryDiagnosticsclassCaptures schema provider discovery issues for startup diagnostics.
SchemaProviderDiscoveryIssuerecordRepresents a schema provider discovery issue.
StellaEndpointAttributeclassMarks a class as a Stella endpoint handler.
StellaMicroserviceOptionsclassOptions for configuring a Stella microservice.
TypedEndpointAdapterclassAdapts typed endpoint handlers to the raw endpoint interface.
ValidateSchemaAttributeclassEnables JSON Schema validation for this endpoint.

class ClaimRequirementConfig

public sealed class ClaimRequirementConfig

Configuration for a claim requirement.

Members

MemberKindSummary
ClaimRequirementConfig()constructorCreates an instance of ClaimRequirementConfig.
TypepropertyGets or sets the claim type.
ValuepropertyGets or sets the claim value.
ToClaimRequirement()methodConverts to a ClaimRequirement model.

constructor ClaimRequirementConfig() #

public ClaimRequirementConfig()

Creates an instance of ClaimRequirementConfig.

property Type #

public string Type { get; set; }

Gets or sets the claim type.

property Value #

public string? Value { get; set; }

Gets or sets the claim value.

method ToClaimRequirement() #

public ClaimRequirement ToClaimRequirement()

Converts to a ClaimRequirement model.

class EndpointDiscoveryService

public sealed class EndpointDiscoveryService : IEndpointDiscoveryService

Service that discovers endpoints and applies YAML configuration overrides.

Members

MemberKindSummary
EndpointDiscoveryService(IEndpointDiscoveryProvider, IMicroserviceYamlLoader, IEndpointOverrideMerger, ILogger<EndpointDiscoveryService>)constructorInitializes a new instance of the EndpointDiscoveryServiceclass.
DiscoverEndpoints()methodDiscovers all endpoints, applying any YAML configuration overrides.

constructor EndpointDiscoveryService(IEndpointDiscoveryProvider, IMicroserviceYamlLoader, IEndpointOverrideMerger, ILogger<EndpointDiscoveryService>) #

public EndpointDiscoveryService(IEndpointDiscoveryProvider discoveryProvider, IMicroserviceYamlLoader yamlLoader, IEndpointOverrideMerger merger, ILogger<EndpointDiscoveryService> logger)

Initializes a new instance of the EndpointDiscoveryServiceclass.

method DiscoverEndpoints() #

public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints, applying any YAML configuration overrides.

Returns

The discovered endpoints with overrides applied.

class EndpointMatch

public sealed class EndpointMatch

Represents a matched endpoint with extracted path parameters.

Members

MemberKindSummary
EndpointMatch()constructorCreates an instance of EndpointMatch.
EndpointpropertyGets the matched endpoint descriptor.
PathParameterspropertyGets the path parameters extracted from the URL.

constructor EndpointMatch() #

public EndpointMatch()

Creates an instance of EndpointMatch.

property Endpoint #

public required EndpointDescriptor Endpoint { get; init; }

Gets the matched endpoint descriptor.

property PathParameters #

public required IReadOnlyDictionary<string, string> PathParameters { get; init; }

Gets the path parameters extracted from the URL.

class EndpointOverrideConfig

public sealed class EndpointOverrideConfig

Configuration for overriding an endpoint’s properties.

Members

MemberKindSummary
EndpointOverrideConfig()constructorCreates an instance of EndpointOverrideConfig.
DefaultTimeoutpropertyGets or sets the default timeout override.
MethodpropertyGets or sets the HTTP method to match.
PathpropertyGets or sets the path to match.
RequiringClaimspropertyGets or sets the claim requirements.
SupportsStreamingpropertyGets or sets whether streaming is supported.
GetDefaultTimeoutAsTimeSpan()methodParses the DefaultTimeout string to a TimeSpan.
TryGetDefaultTimeoutAsTimeSpan(out TimeSpan, out string)methodParses the DefaultTimeout string to a TimeSpan with error output.

constructor EndpointOverrideConfig() #

public EndpointOverrideConfig()

Creates an instance of EndpointOverrideConfig.

property DefaultTimeout #

public string? DefaultTimeout { get; set; }

Gets or sets the default timeout override.

property Method #

public string Method { get; set; }

Gets or sets the HTTP method to match.

property Path #

public string Path { get; set; }

Gets or sets the path to match.

property RequiringClaims #

public List<ClaimRequirementConfig>? RequiringClaims { get; set; }

Gets or sets the claim requirements.

property SupportsStreaming #

public bool? SupportsStreaming { get; set; }

Gets or sets whether streaming is supported.

method GetDefaultTimeoutAsTimeSpan() #

public TimeSpan? GetDefaultTimeoutAsTimeSpan()

Parses the DefaultTimeout string to a TimeSpan.

method TryGetDefaultTimeoutAsTimeSpan(out TimeSpan, out string) #

public bool TryGetDefaultTimeoutAsTimeSpan(out TimeSpan timeout, out string? error)

Parses the DefaultTimeout string to a TimeSpan with error output.

class EndpointOverrideMerger

public sealed class EndpointOverrideMerger : IEndpointOverrideMerger

Merges endpoint overrides from YAML configuration with code defaults.

Members

MemberKindSummary
EndpointOverrideMerger(ILogger<EndpointOverrideMerger>)constructorInitializes a new instance of the EndpointOverrideMergerclass.
Merge(IReadOnlyList<EndpointDescriptor>, MicroserviceYamlConfig)methodMerges YAML overrides with code-defined endpoints.

constructor EndpointOverrideMerger(ILogger<EndpointOverrideMerger>) #

public EndpointOverrideMerger(ILogger<EndpointOverrideMerger> logger)

Initializes a new instance of the EndpointOverrideMergerclass.

method Merge(IReadOnlyList<EndpointDescriptor>, MicroserviceYamlConfig) #

public IReadOnlyList<EndpointDescriptor> Merge(IReadOnlyList<EndpointDescriptor> codeEndpoints, MicroserviceYamlConfig? yamlConfig)

Merges YAML overrides with code-defined endpoints.

Parameters

  • codeEndpoints: The endpoints discovered from code.
  • yamlConfig: The YAML configuration, if any.

Returns

The merged endpoints.

class EndpointRegistry

public sealed class EndpointRegistry : IEndpointRegistry

Default implementation of endpoint registry using path matchers.

Members

MemberKindSummary
EndpointRegistry(bool)constructorInitializes a new instance of the EndpointRegistryclass.
GetAllEndpoints()methodGets all registered endpoints.
Register(EndpointDescriptor)methodRegisters an endpoint descriptor.
RegisterAll(IEnumerable<EndpointDescriptor>)methodRegisters multiple endpoint descriptors.
TryMatch(string, string, out EndpointMatch)methodTries to find a matching endpoint for the given method and path.

constructor EndpointRegistry(bool) #

public EndpointRegistry(bool caseInsensitive = true)

Initializes a new instance of the EndpointRegistryclass.

Parameters

  • caseInsensitive: Whether path matching should be case-insensitive.

method GetAllEndpoints() #

public IReadOnlyList<EndpointDescriptor> GetAllEndpoints()

Gets all registered endpoints.

Returns

All registered endpoint descriptors.

method Register(EndpointDescriptor) #

public void Register(EndpointDescriptor endpoint)

Registers an endpoint descriptor.

Parameters

  • endpoint: The endpoint descriptor to register.

method RegisterAll(IEnumerable<EndpointDescriptor>) #

public void RegisterAll(IEnumerable<EndpointDescriptor> endpoints)

Registers multiple endpoint descriptors.

Parameters

  • endpoints: The endpoint descriptors to register.

method TryMatch(string, string, out EndpointMatch) #

public bool TryMatch(string method, string path, out EndpointMatch? match)

Tries to find a matching endpoint for the given method and path.

Parameters

  • method: The HTTP method.
  • path: The request path.
  • match: The matching endpoint information if found.

Returns

True if a matching endpoint was found.

class GeneratedEndpointDiscoveryProvider

public sealed class GeneratedEndpointDiscoveryProvider : IEndpointDiscoveryProvider, IEndpointSchemaDefinitionProvider

Discovers endpoints using source-generated provider, falling back to reflection. The schema definitions come from the same generated provider as the endpoints, so an endpoint that names a generated schema (ValidateSchemaAttribute) is sent to the gateway together with that schema.

Members

MemberKindSummary
GeneratedEndpointDiscoveryProvider(StellaMicroserviceOptions, ILogger<GeneratedEndpointDiscoveryProvider>, IServiceProviderIsService)constructorInitializes a new instance of the GeneratedEndpointDiscoveryProviderclass.
DiscoverEndpoints()methodDiscovers all endpoints in the application.
DiscoverSchemaDefinitions()methodGets schema definitions keyed by schema identifier.

constructor GeneratedEndpointDiscoveryProvider(StellaMicroserviceOptions, ILogger<GeneratedEndpointDiscoveryProvider>, IServiceProviderIsService) #

public GeneratedEndpointDiscoveryProvider(StellaMicroserviceOptions options, ILogger<GeneratedEndpointDiscoveryProvider> logger, IServiceProviderIsService? serviceProviderIsService = null)

Initializes a new instance of the GeneratedEndpointDiscoveryProviderclass.

method DiscoverEndpoints() #

public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints in the application.

Returns

The discovered endpoints.

method DiscoverSchemaDefinitions() #

public IReadOnlyDictionary<string, SchemaDefinition> DiscoverSchemaDefinitions()

Gets schema definitions keyed by schema identifier.

Remarks

Returns the schemas of the generated provider that GeneratedEndpointDiscoveryProvider.DiscoverEndpoints()uses, or none when discovery falls back to reflection (reflection discovery names no schemas).

class HeaderCollection

public sealed class HeaderCollection : IHeaderCollection

Default implementation of header collection.

Members

MemberKindSummary
HeaderCollection()constructorInitializes a new instance of the HeaderCollectionclass.
HeaderCollection(IEnumerable<KeyValuePair<string, string>>)constructorInitializes a new instance from key-value pairs.
EmptyfieldGets an empty header collection.
this[string]indexerGets a header value by key.
Add(string, string)methodAdds a header value.
ContainsKey(string)methodChecks if a header exists.
GetEnumerator()methodSee IEnumerable<T>.GetEnumerator().
GetValues(string)methodGets all values for a header key.
Set(string, string)methodSets a header, replacing any existing values.
TryGetValue(string, out string)methodTries to get a header value.

constructor HeaderCollection() #

public HeaderCollection()

Initializes a new instance of the HeaderCollectionclass.

constructor HeaderCollection(IEnumerable<KeyValuePair<string, string>>) #

public HeaderCollection(IEnumerable<KeyValuePair<string, string>> headers)

Initializes a new instance from key-value pairs.

field Empty #

public static readonly HeaderCollection Empty

Gets an empty header collection.

indexer this[string] #

public string? this[string key] { get; }

Gets a header value by key.

Parameters

  • key: The header key (case-insensitive).

Returns

The header value, or null if not found.

method Add(string, string) #

public void Add(string key, string value)

Adds a header value.

Parameters

  • key: The header key.
  • value: The header value.

method ContainsKey(string) #

public bool ContainsKey(string key)

Checks if a header exists.

Parameters

  • key: The header key.

Returns

True if the header exists.

method GetEnumerator() #

public IEnumerator<KeyValuePair<string, string>> GetEnumerator()

See IEnumerable<T>.GetEnumerator().

method GetValues(string) #

public IEnumerable<string> GetValues(string key)

Gets all values for a header key.

Parameters

  • key: The header key (case-insensitive).

Returns

All values for the key.

method Set(string, string) #

public void Set(string key, string value)

Sets a header, replacing any existing values.

Parameters

  • key: The header key.
  • value: The header value.

method TryGetValue(string, out string) #

public bool TryGetValue(string key, out string? value)

Tries to get a header value.

Parameters

  • key: The header key.
  • value: The header value if found.

Returns

True if the header was found.

interface IEndpointDiscoveryProvider

public interface IEndpointDiscoveryProvider

Provides endpoint discovery functionality.

Members

MemberKindSummary
DiscoverEndpoints()methodDiscovers all endpoints in the application.

method DiscoverEndpoints() #

IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints in the application.

Returns

The discovered endpoints.

interface IEndpointDiscoveryService

public interface IEndpointDiscoveryService

Interface for discovering endpoints with YAML configuration support.

Members

MemberKindSummary
DiscoverEndpoints()methodDiscovers all endpoints, applying any YAML configuration overrides.

method DiscoverEndpoints() #

IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints, applying any YAML configuration overrides.

Returns

The discovered endpoints with overrides applied.

interface IEndpointOverrideMerger

public interface IEndpointOverrideMerger

Interface for merging endpoint overrides from YAML configuration.

Members

MemberKindSummary
Merge(IReadOnlyList<EndpointDescriptor>, MicroserviceYamlConfig)methodMerges YAML overrides with code-defined endpoints.

method Merge(IReadOnlyList<EndpointDescriptor>, MicroserviceYamlConfig) #

IReadOnlyList<EndpointDescriptor> Merge(IReadOnlyList<EndpointDescriptor> codeEndpoints, MicroserviceYamlConfig? yamlConfig)

Merges YAML overrides with code-defined endpoints.

Parameters

  • codeEndpoints: The endpoints discovered from code.
  • yamlConfig: The YAML configuration, if any.

Returns

The merged endpoints.

interface IEndpointRegistry

public interface IEndpointRegistry

Registry for looking up endpoint handlers by method and path.

Members

MemberKindSummary
GetAllEndpoints()methodGets all registered endpoints.
TryMatch(string, string, out EndpointMatch)methodTries to find a matching endpoint for the given method and path.

method GetAllEndpoints() #

IReadOnlyList<EndpointDescriptor> GetAllEndpoints()

Gets all registered endpoints.

Returns

All registered endpoint descriptors.

method TryMatch(string, string, out EndpointMatch) #

bool TryMatch(string method, string path, out EndpointMatch? match)

Tries to find a matching endpoint for the given method and path.

Parameters

  • method: The HTTP method.
  • path: The request path.
  • match: The matching endpoint information if found.

Returns

True if a matching endpoint was found.

interface IEndpointSchemaDefinitionProvider

public interface IEndpointSchemaDefinitionProvider

Optional provider for endpoint JSON schema definitions discovered at runtime.

Members

MemberKindSummary
DiscoverSchemaDefinitions()methodGets schema definitions keyed by schema identifier.

method DiscoverSchemaDefinitions() #

IReadOnlyDictionary<string, SchemaDefinition> DiscoverSchemaDefinitions()

Gets schema definitions keyed by schema identifier.

interface IGeneratedEndpointProvider

public interface IGeneratedEndpointProvider

Interface implemented by the source-generated endpoint provider.

Members

MemberKindSummary
GetEndpoints()methodGets all discovered endpoint descriptors.
GetHandlerTypes()methodGets all handler types for endpoint discovery.
GetSchemaDefinitions()methodGets the schema definitions for OpenAPI and validation.
RegisterHandlers(IServiceCollection)methodRegisters all endpoint handlers with the service collection.

method GetEndpoints() #

IReadOnlyList<EndpointDescriptor> GetEndpoints()

Gets all discovered endpoint descriptors.

method GetHandlerTypes() #

IReadOnlyList<Type> GetHandlerTypes()

Gets all handler types for endpoint discovery.

method GetSchemaDefinitions() #

IReadOnlyDictionary<string, SchemaDefinition> GetSchemaDefinitions()

Gets the schema definitions for OpenAPI and validation. Keys are schema IDs, values are JSON Schema definitions.

method RegisterHandlers(IServiceCollection) #

void RegisterHandlers(IServiceCollection services)

Registers all endpoint handlers with the service collection.

interface IHeaderCollection

public interface IHeaderCollection : IEnumerable<KeyValuePair<string, string>>

Abstraction for HTTP-style header collection.

Members

MemberKindSummary
this[string]indexerGets a header value by key.
ContainsKey(string)methodChecks if a header exists.
GetValues(string)methodGets all values for a header key.
TryGetValue(string, out string)methodTries to get a header value.

indexer this[string] #

string? this[string key] { get; }

Gets a header value by key.

Parameters

  • key: The header key (case-insensitive).

Returns

The header value, or null if not found.

method ContainsKey(string) #

bool ContainsKey(string key)

Checks if a header exists.

Parameters

  • key: The header key.

Returns

True if the header exists.

method GetValues(string) #

IEnumerable<string> GetValues(string key)

Gets all values for a header key.

Parameters

  • key: The header key (case-insensitive).

Returns

All values for the key.

method TryGetValue(string, out string) #

bool TryGetValue(string key, out string? value)

Tries to get a header value.

Parameters

  • key: The header key.
  • value: The header value if found.

Returns

True if the header was found.

interface IMicroserviceYamlLoader

public interface IMicroserviceYamlLoader

Interface for loading microservice YAML configuration.

Members

MemberKindSummary
Load()methodLoads the microservice configuration from YAML.

method Load() #

MicroserviceYamlConfig? Load()

Loads the microservice configuration from YAML.

Returns

The configuration, or null if no file is configured or file doesn’t exist.

interface IRawStellaEndpoint

public interface IRawStellaEndpoint : IStellaEndpoint

Interface for a raw Stella endpoint that handles requests with full context.

Members

MemberKindSummary
HandleAsync(RawRequestContext, CancellationToken)methodHandles the raw request with full context.

method HandleAsync(RawRequestContext, CancellationToken) #

Task<RawResponse> HandleAsync(RawRequestContext context, CancellationToken cancellationToken)

Handles the raw request with full context.

Parameters

  • context: The request context including headers, path parameters, and body stream.
  • cancellationToken: Cancellation token.

Returns

The raw response including status code, headers, and body stream.

interface IRequestDispatcher

public interface IRequestDispatcher

Abstraction for dispatching Router request frames to handlers.

Members

MemberKindSummary
CanHandle(string, string)methodChecks if this dispatcher can handle the given request.
DispatchAsync(RequestFrame, CancellationToken)methodDispatches a REQUEST frame and returns a RESPONSE frame.

method CanHandle(string, string) #

bool CanHandle(string method, string path)

Checks if this dispatcher can handle the given request. Used by composite dispatchers to route to the appropriate handler.

Parameters

  • method: HTTP method.
  • path: Request path (without query string).

Returns

True if this dispatcher can handle the request.

method DispatchAsync(RequestFrame, CancellationToken) #

Task<ResponseFrame> DispatchAsync(RequestFrame request, CancellationToken cancellationToken)

Dispatches a REQUEST frame and returns a RESPONSE frame.

Parameters

  • request: The incoming REQUEST frame.
  • cancellationToken: Cancellation token.

Returns

The RESPONSE frame.

interface IRouterConnectionManager

public interface IRouterConnectionManager

Manages connections to router gateways.

Members

MemberKindSummary
ConnectionspropertyGets the current connection states.
InFlightRequestCountpropertyGets the number of requests currently being processed by this instance.
BeginDrainAsync(CancellationToken)methodBegins graceful draining by reporting Draining to the router and emitting an immediate heartbeat so gateways stop sending new work.
SendGoodbyeAsync(CancellationToken)methodSends a best-effort Goodbye frame to request prompt deregistration.
StartAsync(CancellationToken)methodStarts the connection manager.
StopAsync(CancellationToken)methodStops the connection manager.

property Connections #

IReadOnlyList<ConnectionState> Connections { get; }

Gets the current connection states.

property InFlightRequestCount #

int InFlightRequestCount { get; }

Gets the number of requests currently being processed by this instance.

method BeginDrainAsync(CancellationToken) #

Task BeginDrainAsync(CancellationToken cancellationToken)

Begins graceful draining by reporting Draining to the router and emitting an immediate heartbeat so gateways stop sending new work.

Parameters

  • cancellationToken: Cancellation token.

method SendGoodbyeAsync(CancellationToken) #

Task SendGoodbyeAsync(CancellationToken cancellationToken)

Sends a best-effort Goodbye frame to request prompt deregistration. Calling this after the connection has already been torn down is a no-op.

Parameters

  • cancellationToken: Cancellation token.

method StartAsync(CancellationToken) #

Task StartAsync(CancellationToken cancellationToken)

Starts the connection manager.

Parameters

  • cancellationToken: Cancellation token.

method StopAsync(CancellationToken) #

Task StopAsync(CancellationToken cancellationToken)

Stops the connection manager.

Parameters

  • cancellationToken: Cancellation token.

interface IStellaEndpoint

public interface IStellaEndpoint

Marker interface for all Stella endpoints.

interface IStellaEndpoint<TRequest, TResponse>

public interface IStellaEndpoint<TRequest, TResponse> : IStellaEndpoint

Interface for a typed Stella endpoint with request and response.

Type parameters

  • TRequest: The request type.
  • TResponse: The response type.

Members

MemberKindSummary
HandleAsync(TRequest, CancellationToken)methodHandles the request.

method HandleAsync(TRequest, CancellationToken) #

Task<TResponse> HandleAsync(TRequest request, CancellationToken cancellationToken)

Handles the request.

Parameters

  • request: The request.
  • cancellationToken: Cancellation token.

Returns

The response.

interface IStellaEndpoint<TResponse>

public interface IStellaEndpoint<TResponse> : IStellaEndpoint

Interface for a typed Stella endpoint with response only (no request body).

Type parameters

  • TResponse: The response type.

Members

MemberKindSummary
HandleAsync(CancellationToken)methodHandles the request.

method HandleAsync(CancellationToken) #

Task<TResponse> HandleAsync(CancellationToken cancellationToken)

Handles the request.

Parameters

  • cancellationToken: Cancellation token.

Returns

The response.

class InflightRequestTracker

public sealed class InflightRequestTracker : IDisposable

Tracks in-flight requests and manages their cancellation tokens.

Members

MemberKindSummary
InflightRequestTracker(ILogger<InflightRequestTracker>)constructorInitializes a new instance of the InflightRequestTrackerclass.
CountpropertyGets the count of in-flight requests.
Cancel(Guid, string)methodCancels a specific request.
CancelAll(string)methodCancels all in-flight requests.
Complete(Guid)methodMarks a request as completed and removes it from tracking.
Dispose()methodSee IDisposable.Dispose().
Track(Guid)methodStarts tracking a request and returns a cancellation token for it.

constructor InflightRequestTracker(ILogger<InflightRequestTracker>) #

public InflightRequestTracker(ILogger<InflightRequestTracker> logger)

Initializes a new instance of the InflightRequestTrackerclass.

property Count #

public int Count { get; }

Gets the count of in-flight requests.

method Cancel(Guid, string) #

public bool Cancel(Guid correlationId, string? reason)

Cancels a specific request.

Parameters

  • correlationId: The correlation ID of the request to cancel.
  • reason: The reason for cancellation.

Returns

True if the request was found and cancelled; otherwise false.

method CancelAll(string) #

public void CancelAll(string reason)

Cancels all in-flight requests.

Parameters

  • reason: The reason for cancellation.

method Complete(Guid) #

public void Complete(Guid correlationId)

Marks a request as completed and removes it from tracking.

Parameters

  • correlationId: The correlation ID of the completed request.

method Dispose() #

public void Dispose()

See IDisposable.Dispose().

method Track(Guid) #

public CancellationToken Track(Guid correlationId)

Starts tracking a request and returns a cancellation token for it.

Parameters

  • correlationId: The correlation ID of the request.

Returns

A cancellation token that will be triggered if the request is cancelled.

class MicroserviceHostedService

public sealed class MicroserviceHostedService : IHostedService, IDisposable

Hosted service that manages the microservice lifecycle.

Members

MemberKindSummary
MicroserviceHostedService(IRouterConnectionManager, IHostApplicationLifetime, ILogger<MicroserviceHostedService>, IOptions<StellaMicroserviceOptions>, SchemaProviderDiscoveryDiagnostics)constructorInitializes a new instance of the MicroserviceHostedServiceclass.
Dispose()methodSee IDisposable.Dispose().
StartAsync(CancellationToken)methodSee IHostedService.StartAsync(CancellationToken).
StopAsync(CancellationToken)methodSee IHostedService.StopAsync(CancellationToken).

constructor MicroserviceHostedService(IRouterConnectionManager, IHostApplicationLifetime, ILogger<MicroserviceHostedService>, IOptions<StellaMicroserviceOptions>, SchemaProviderDiscoveryDiagnostics) #

public MicroserviceHostedService(IRouterConnectionManager connectionManager, IHostApplicationLifetime applicationLifetime, ILogger<MicroserviceHostedService> logger, IOptions<StellaMicroserviceOptions> options, SchemaProviderDiscoveryDiagnostics? schemaDiagnostics = null)

Initializes a new instance of the MicroserviceHostedServiceclass.

method Dispose() #

public void Dispose()

See IDisposable.Dispose().

method StartAsync(CancellationToken) #

public Task StartAsync(CancellationToken cancellationToken)

See IHostedService.StartAsync(CancellationToken).

method StopAsync(CancellationToken) #

public Task StopAsync(CancellationToken cancellationToken)

See IHostedService.StopAsync(CancellationToken).

class MicroserviceServiceCollectionExtensions

public static class MicroserviceServiceCollectionExtensions

Extension methods for registering Stella microservice services.

Members

MemberKindSummary
AddStellaEndpoint<THandler>(IServiceCollection)extension methodRegisters an endpoint handler type for dependency injection.
AddStellaMicroservice(IServiceCollection, Action<StellaMicroserviceOptions>)extension methodAdds Stella microservice services to the service collection.
AddStellaMicroservice<TDiscovery>(IServiceCollection, Action<StellaMicroserviceOptions>)extension methodAdds Stella microservice services with a custom endpoint discovery provider.
AddStellaSchemaProvider<TProvider>(IServiceCollection)extension methodRegisters a generated schema provider for schema validation.

extension method AddStellaEndpoint<THandler>(IServiceCollection) #

public static IServiceCollection AddStellaEndpoint<THandler>(this IServiceCollection services) where THandler : class, IStellaEndpoint

Registers an endpoint handler type for dependency injection.

Type parameters

  • THandler: The endpoint handler type.

Parameters

  • services: The service collection.

Returns

The service collection for chaining.

extension method AddStellaMicroservice(IServiceCollection, Action<StellaMicroserviceOptions>) #

public static IServiceCollection AddStellaMicroservice(this IServiceCollection services, Action<StellaMicroserviceOptions> configure)

Adds Stella microservice services to the service collection.

Parameters

  • services: The service collection.
  • configure: Action to configure the microservice options.

Returns

The service collection for chaining.

extension method AddStellaMicroservice<TDiscovery>(IServiceCollection, Action<StellaMicroserviceOptions>) #

public static IServiceCollection AddStellaMicroservice<TDiscovery>(this IServiceCollection services, Action<StellaMicroserviceOptions> configure) where TDiscovery : class, IEndpointDiscoveryProvider

Adds Stella microservice services with a custom endpoint discovery provider.

Type parameters

  • TDiscovery: The endpoint discovery provider type.

Parameters

  • services: The service collection.
  • configure: Action to configure the microservice options.

Returns

The service collection for chaining.

extension method AddStellaSchemaProvider<TProvider>(IServiceCollection) #

public static IServiceCollection AddStellaSchemaProvider<TProvider>(this IServiceCollection services) where TProvider : class, IGeneratedSchemaProvider

Registers a generated schema provider for schema validation.

Type parameters

  • TProvider: The generated schema provider type.

Parameters

  • services: The service collection.

Returns

The service collection for chaining.

class MicroserviceYamlConfig

public sealed class MicroserviceYamlConfig

Root configuration for microservice endpoint overrides loaded from YAML.

Members

MemberKindSummary
MicroserviceYamlConfig()constructorCreates an instance of MicroserviceYamlConfig.
EndpointspropertyGets or sets the endpoint override configurations.

constructor MicroserviceYamlConfig() #

public MicroserviceYamlConfig()

Creates an instance of MicroserviceYamlConfig.

property Endpoints #

public List<EndpointOverrideConfig> Endpoints { get; set; }

Gets or sets the endpoint override configurations.

class MicroserviceYamlLoader

public sealed class MicroserviceYamlLoader : IMicroserviceYamlLoader

Loads microservice configuration from a YAML file.

Members

MemberKindSummary
MicroserviceYamlLoader(StellaMicroserviceOptions, ILogger<MicroserviceYamlLoader>)constructorInitializes a new instance of the MicroserviceYamlLoaderclass.
Load()methodLoads the microservice configuration from YAML.

constructor MicroserviceYamlLoader(StellaMicroserviceOptions, ILogger<MicroserviceYamlLoader>) #

public MicroserviceYamlLoader(StellaMicroserviceOptions options, ILogger<MicroserviceYamlLoader> logger)

Initializes a new instance of the MicroserviceYamlLoaderclass.

method Load() #

public MicroserviceYamlConfig? Load()

Loads the microservice configuration from YAML.

Returns

The configuration, or null if no file is configured or file doesn’t exist.

class RawRequestContext

public sealed class RawRequestContext

Context for a raw request.

Members

MemberKindSummary
RawRequestContext()constructorCreates an instance of RawRequestContext.
BodypropertyGets the request body stream.
CancellationTokenpropertyGets the cancellation token.
CorrelationIdpropertyGets the correlation ID for request tracking.
HeaderspropertyGets the request headers.
MethodpropertyGets the HTTP method.
PathpropertyGets the request path.
PathParameterspropertyGets the path parameters extracted from route templates.
QueryParameterspropertyGets the query parameters extracted from the request path.

constructor RawRequestContext() #

public RawRequestContext()

Creates an instance of RawRequestContext.

property Body #

public Stream Body { get; init; }

Gets the request body stream.

property CancellationToken #

public CancellationToken CancellationToken { get; init; }

Gets the cancellation token.

property CorrelationId #

public string? CorrelationId { get; init; }

Gets the correlation ID for request tracking.

property Headers #

public IHeaderCollection Headers { get; init; }

Gets the request headers.

property Method #

public string Method { get; init; }

Gets the HTTP method.

property Path #

public string Path { get; init; }

Gets the request path.

property PathParameters #

public IReadOnlyDictionary<string, string> PathParameters { get; init; }

Gets the path parameters extracted from route templates.

property QueryParameters #

public IReadOnlyDictionary<string, string> QueryParameters { get; init; }

Gets the query parameters extracted from the request path.

class RawResponse

public sealed class RawResponse

Represents a raw response from an endpoint.

Members

MemberKindSummary
RawResponse()constructorCreates an instance of RawResponse.
BodypropertyGets or sets the response body stream.
HeaderspropertyGets or sets the response headers.
StatusCodepropertyGets or sets the HTTP status code.
BadRequest(string)methodCreates a 400 Bad Request response.
Error(int, string)methodCreates an error response with a message body.
InternalError(string)methodCreates a 500 Internal Server Error response.
NoContent()methodCreates a 204 No Content response.
NotFound(string)methodCreates a 404 Not Found response.
Ok(Stream)methodCreates a 200 OK response with a body.
Ok(byte[])methodCreates a 200 OK response with a byte array body.
Ok(string)methodCreates a 200 OK response with a string body.

constructor RawResponse() #

public RawResponse()

Creates an instance of RawResponse.

property Body #

public Stream Body { get; init; }

Gets or sets the response body stream.

property Headers #

public IHeaderCollection Headers { get; init; }

Gets or sets the response headers.

property StatusCode #

public int StatusCode { get; init; }

Gets or sets the HTTP status code.

method BadRequest(string) #

public static RawResponse BadRequest(string? message = null)

Creates a 400 Bad Request response.

method Error(int, string) #

public static RawResponse Error(int statusCode, string message)

Creates an error response with a message body.

method InternalError(string) #

public static RawResponse InternalError(string? message = null)

Creates a 500 Internal Server Error response.

method NoContent() #

public static RawResponse NoContent()

Creates a 204 No Content response.

method NotFound(string) #

public static RawResponse NotFound(string? message = null)

Creates a 404 Not Found response.

method Ok(Stream) #

public static RawResponse Ok(Stream body)

Creates a 200 OK response with a body.

method Ok(byte[]) #

public static RawResponse Ok(byte[] body)

Creates a 200 OK response with a byte array body.

method Ok(string) #

public static RawResponse Ok(string body)

Creates a 200 OK response with a string body.

class ReflectionEndpointDiscoveryProvider

public sealed class ReflectionEndpointDiscoveryProvider : IEndpointDiscoveryProvider

Discovers endpoints using runtime reflection.

Members

MemberKindSummary
ReflectionEndpointDiscoveryProvider(StellaMicroserviceOptions, IEnumerable<Assembly>, IServiceProviderIsService, ILogger)constructorInitializes a new instance of the ReflectionEndpointDiscoveryProviderclass.
DiscoverEndpoints()methodDiscovers all endpoints in the application.

constructor ReflectionEndpointDiscoveryProvider(StellaMicroserviceOptions, IEnumerable<Assembly>, IServiceProviderIsService, ILogger) #

public ReflectionEndpointDiscoveryProvider(StellaMicroserviceOptions options, IEnumerable<Assembly>? assemblies = null, IServiceProviderIsService? serviceProviderIsService = null, ILogger? logger = null)

Initializes a new instance of the ReflectionEndpointDiscoveryProviderclass.

Parameters

  • options: The microservice options.
  • assemblies: The assemblies to scan for endpoints.
  • serviceProviderIsService: When set, an endpoint class that the service provider cannot resolve is skipped.
  • logger: Receives a warning for each assembly that cannot be scanned.

method DiscoverEndpoints() #

public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints in the application.

Returns

The discovered endpoints.

class RequestDispatcher

public sealed class RequestDispatcher : IRequestDispatcher

Dispatches incoming REQUEST frames to the appropriate endpoint handlers. This is the default dispatcher for [StellaEndpoint] attributed handlers.

Members

MemberKindSummary
RequestDispatcher(IEndpointRegistry, IServiceProvider, ILogger<RequestDispatcher>, ISchemaRegistry, IRequestSchemaValidator, JsonSerializerOptions)constructorInitializes a new instance of the RequestDispatcherclass.
CanHandle(string, string)methodChecks if this dispatcher can handle the given request.
DispatchAsync(RequestFrame, CancellationToken)methodDispatches a REQUEST frame and returns a RESPONSE frame.

constructor RequestDispatcher(IEndpointRegistry, IServiceProvider, ILogger<RequestDispatcher>, ISchemaRegistry, IRequestSchemaValidator, JsonSerializerOptions) #

public RequestDispatcher(IEndpointRegistry registry, IServiceProvider serviceProvider, ILogger<RequestDispatcher> logger, ISchemaRegistry? schemaRegistry = null, IRequestSchemaValidator? schemaValidator = null, JsonSerializerOptions? jsonOptions = null)

Initializes a new instance of the RequestDispatcherclass.

Parameters

  • registry: The endpoint registry.
  • serviceProvider: The service provider for resolving handlers.
  • logger: The logger.
  • schemaRegistry: Optional schema registry for validation.
  • schemaValidator: Optional schema validator.
  • jsonOptions: Optional JSON serialization options.

method CanHandle(string, string) #

public bool CanHandle(string method, string path)

Checks if this dispatcher can handle the given request. Used by composite dispatchers to route to the appropriate handler.

Parameters

  • method: HTTP method.
  • path: Request path (without query string).

Returns

True if this dispatcher can handle the request.

method DispatchAsync(RequestFrame, CancellationToken) #

public Task<ResponseFrame> DispatchAsync(RequestFrame request, CancellationToken cancellationToken)

Dispatches a REQUEST frame and returns a RESPONSE frame.

Parameters

  • request: The incoming REQUEST frame.
  • cancellationToken: Cancellation token.

Returns

The RESPONSE frame.

class RouterConnectionManager

public sealed class RouterConnectionManager : IRouterConnectionManager, IDisposable

Manages connections to router gateways.

Members

MemberKindSummary
RouterConnectionManager(IOptions<StellaMicroserviceOptions>, IEndpointDiscoveryProvider, IRequestDispatcher, IMicroserviceTransport, ILogger<RouterConnectionManager>, IGeneratedEndpointProvider, IEndpointDiscoveryService)constructorInitializes a new instance of the RouterConnectionManagerclass.
ConnectionspropertyGets the current connection states.
CurrentStatuspropertyGets or sets the current health status reported by this instance.
ErrorRatepropertyGets or sets the error rate (0.0 to 1.0).
InFlightRequestCountpropertyGets or sets the count of in-flight requests.
BeginDrainAsync(CancellationToken)methodBegins graceful draining by reporting Draining to the router and emitting an immediate heartbeat so gateways stop sending new work.
Dispose()methodSee IDisposable.Dispose().
SendGoodbyeAsync(CancellationToken)methodSends a best-effort Goodbye frame to request prompt deregistration.
StartAsync(CancellationToken)methodStarts the connection manager.
StopAsync(CancellationToken)methodStops the connection manager.

constructor RouterConnectionManager(IOptions<StellaMicroserviceOptions>, IEndpointDiscoveryProvider, IRequestDispatcher, IMicroserviceTransport, ILogger<RouterConnectionManager>, IGeneratedEndpointProvider, IEndpointDiscoveryService) #

public RouterConnectionManager(IOptions<StellaMicroserviceOptions> options, IEndpointDiscoveryProvider endpointDiscovery, IRequestDispatcher requestDispatcher, IMicroserviceTransport? microserviceTransport, ILogger<RouterConnectionManager> logger, IGeneratedEndpointProvider? generatedProvider = null, IEndpointDiscoveryService? endpointDiscoveryService = null)

Initializes a new instance of the RouterConnectionManagerclass.

Parameters

  • options: The microservice options.
  • endpointDiscovery: The endpoint discovery provider.
  • requestDispatcher: The request dispatcher.
  • microserviceTransport: The transport to the gateways.
  • logger: The logger.
  • generatedProvider: The source-generated endpoint provider, when present.
  • endpointDiscoveryService: The endpoint discovery with the StellaMicroserviceOptions.ConfigFilePathoverrides applied, when registered (AddStellaMicroservice registers it). The endpoints sent in HELLO come from it, so the gateway routes and authorizes by the same timeouts, streaming flags and required claims the service dispatches with; without it, the endpoints of endpointDiscovery are sent unchanged.

property Connections #

public IReadOnlyList<ConnectionState> Connections { get; }

Gets the current connection states.

property CurrentStatus #

public InstanceHealthStatus CurrentStatus { get; set; }

Gets or sets the current health status reported by this instance.

property ErrorRate #

public double ErrorRate { get; set; }

Gets or sets the error rate (0.0 to 1.0).

property InFlightRequestCount #

public int InFlightRequestCount { get; set; }

Gets or sets the count of in-flight requests.

method BeginDrainAsync(CancellationToken) #

public Task BeginDrainAsync(CancellationToken cancellationToken)

Begins graceful draining by reporting Draining to the router and emitting an immediate heartbeat so gateways stop sending new work.

Parameters

  • cancellationToken: Cancellation token.

method Dispose() #

public void Dispose()

See IDisposable.Dispose().

method SendGoodbyeAsync(CancellationToken) #

public Task SendGoodbyeAsync(CancellationToken cancellationToken)

Sends a best-effort Goodbye frame to request prompt deregistration. Calling this after the connection has already been torn down is a no-op.

Parameters

  • cancellationToken: Cancellation token.

method StartAsync(CancellationToken) #

public Task StartAsync(CancellationToken cancellationToken)

Starts the connection manager.

Parameters

  • cancellationToken: Cancellation token.

method StopAsync(CancellationToken) #

public Task StopAsync(CancellationToken cancellationToken)

Stops the connection manager.

Parameters

  • cancellationToken: Cancellation token.

class RouterEndpointConfig

public sealed class RouterEndpointConfig

Configuration for a router endpoint.

Members

MemberKindSummary
RouterEndpointConfig()constructorCreates an instance of RouterEndpointConfig.
HostpropertyGets or sets the router host.
PortpropertyGets or sets the router port.
TransportTypepropertyGets or sets the transport type to use.

constructor RouterEndpointConfig() #

public RouterEndpointConfig()

Creates an instance of RouterEndpointConfig.

property Host #

public required string Host { get; set; }

Gets or sets the router host.

property Port #

public required int Port { get; set; }

Gets or sets the router port.

property TransportType #

public TransportType TransportType { get; set; }

Gets or sets the transport type to use.

class SchemaProviderDiscoveryDiagnostics

public sealed class SchemaProviderDiscoveryDiagnostics

Captures schema provider discovery issues for startup diagnostics.

Members

MemberKindSummary
SchemaProviderDiscoveryDiagnostics(IReadOnlyList<SchemaProviderDiscoveryIssue>)constructorInitializes a new instance of the SchemaProviderDiscoveryDiagnosticsclass.
IssuespropertyGets the discovery issues.

constructor SchemaProviderDiscoveryDiagnostics(IReadOnlyList<SchemaProviderDiscoveryIssue>) #

public SchemaProviderDiscoveryDiagnostics(IReadOnlyList<SchemaProviderDiscoveryIssue> issues)

Initializes a new instance of the SchemaProviderDiscoveryDiagnosticsclass.

Parameters

  • issues: The discovery issues.

property Issues #

public IReadOnlyList<SchemaProviderDiscoveryIssue> Issues { get; }

Gets the discovery issues.

record SchemaProviderDiscoveryIssue

public sealed record SchemaProviderDiscoveryIssue

Represents a schema provider discovery issue.

Parameters

  • AssemblyName: The assembly whose schema provider could not be read.
  • Message: What went wrong.

Members

MemberKindSummary
SchemaProviderDiscoveryIssue(string, string)constructorRepresents a schema provider discovery issue.
AssemblyNamepropertyThe assembly whose schema provider could not be read.
MessagepropertyWhat went wrong.

constructor SchemaProviderDiscoveryIssue(string, string) #

public SchemaProviderDiscoveryIssue(string AssemblyName, string Message)

Represents a schema provider discovery issue.

Parameters

  • AssemblyName: The assembly whose schema provider could not be read.
  • Message: What went wrong.

property AssemblyName #

public string AssemblyName { get; init; }

The assembly whose schema provider could not be read.

property Message #

public string Message { get; init; }

What went wrong.

class StellaEndpointAttribute

public sealed class StellaEndpointAttribute : Attribute

Marks a class as a Stella endpoint handler.

Applies to: Class. Allow multiple: no. Inherited: no.

Members

MemberKindSummary
StellaEndpointAttribute(string, string)constructorInitializes a new instance of the StellaEndpointAttributeclass.
MethodpropertyGets the HTTP method for this endpoint.
PathpropertyGets the path for this endpoint.
RequiredClaimspropertyGets or sets the required claim types for this endpoint.
SupportsStreamingpropertyGets or sets whether this endpoint supports streaming.
TimeoutSecondspropertyGets or sets the default timeout in seconds.

constructor StellaEndpointAttribute(string, string) #

public StellaEndpointAttribute(string method, string path)

Initializes a new instance of the StellaEndpointAttributeclass.

Parameters

  • method: The HTTP method.
  • path: The endpoint path.

property Method #

public string Method { get; }

Gets the HTTP method for this endpoint.

property Path #

public string Path { get; }

Gets the path for this endpoint.

property RequiredClaims #

public string[] RequiredClaims { get; set; }

Gets or sets the required claim types for this endpoint.

property SupportsStreaming #

public bool SupportsStreaming { get; set; }

Gets or sets whether this endpoint supports streaming. Default: false.

property TimeoutSeconds #

public int TimeoutSeconds { get; set; }

Gets or sets the default timeout in seconds. Default: 30 seconds.

class StellaMicroserviceOptions

public sealed class StellaMicroserviceOptions

Options for configuring a Stella microservice.

Members

MemberKindSummary
StellaMicroserviceOptions()constructorCreates an instance of StellaMicroserviceOptions.
ConfigFilePathpropertyGets or sets the optional path to a YAML config file for endpoint overrides.
ContactInfopropertyGets or sets the contact information for OpenAPI documentation.
DrainDeadlinepropertyGets or sets how long shutdown waits for in-flight requests to finish after the instance starts reporting Draining.
DrainPollIntervalpropertyGets or sets how often shutdown polls the in-flight request count during the drain deadline.
HeartbeatIntervalpropertyGets or sets the heartbeat interval.
InstanceIdpropertyGets or sets the unique instance identifier.
ReconnectBackoffInitialpropertyGets or sets the initial reconnect delay.
ReconnectBackoffMaxpropertyGets or sets the maximum reconnect backoff.
RegionpropertyGets or sets the region where this instance is deployed.
RouterspropertyGets the router endpoints to connect to.
ServiceDescriptionpropertyGets or sets the service description for OpenAPI documentation.
ServiceNamepropertyGets or sets the service name.
VersionpropertyGets or sets the semantic version.
WeightpropertyGets or sets the routing weight this instance advertises in HELLO.
Validate()methodValidates the options and throws if invalid.

constructor StellaMicroserviceOptions() #

public StellaMicroserviceOptions()

Creates an instance of StellaMicroserviceOptions.

property ConfigFilePath #

public string? ConfigFilePath { get; set; }

Gets or sets the optional path to a YAML config file for endpoint overrides.

property ContactInfo #

public string? ContactInfo { get; set; }

Gets or sets the contact information for OpenAPI documentation.

property DrainDeadline #

public TimeSpan DrainDeadline { get; set; }

Gets or sets how long shutdown waits for in-flight requests to finish after the instance starts reporting Draining. Default: 25 seconds.

property DrainPollInterval #

public TimeSpan DrainPollInterval { get; set; }

Gets or sets how often shutdown polls the in-flight request count during the drain deadline. Default: 100 milliseconds.

property HeartbeatInterval #

public TimeSpan HeartbeatInterval { get; set; }

Gets or sets the heartbeat interval. Default: 10 seconds, below the router gateway host’s default degraded threshold (20 seconds in effect) and a third of its default stale threshold (30 seconds), so a service with the defaults is never reported degraded or stale between heartbeats. A longer interval needs the gateway’s Gateway:Health thresholds raised to match; the service logs a warning at start-up when the interval is longer than that stale threshold.

property InstanceId #

public string InstanceId { get; set; }

Gets or sets the unique instance identifier. Auto-generated if not provided.

property ReconnectBackoffInitial #

public TimeSpan ReconnectBackoffInitial { get; set; }

Gets or sets the initial reconnect delay. Default: 1 second.

property ReconnectBackoffMax #

public TimeSpan ReconnectBackoffMax { get; set; }

Gets or sets the maximum reconnect backoff. Default: 1 minute.

property Region #

public required string Region { get; set; }

Gets or sets the region where this instance is deployed.

property Routers #

public List<RouterEndpointConfig> Routers { get; set; }

Gets the router endpoints to connect to. At least one router endpoint is required.

property ServiceDescription #

public string? ServiceDescription { get; set; }

Gets or sets the service description for OpenAPI documentation.

property ServiceName #

public required string ServiceName { get; set; }

Gets or sets the service name.

property Version #

public required string Version { get; set; }

Gets or sets the semantic version. Must be valid semver (e.g., “1.0.0”, “2.1.0-beta.1”).

property Weight #

public int Weight { get; set; }

Gets or sets the routing weight this instance advertises in HELLO.

method Validate() #

public void Validate()

Validates the options and throws if invalid.

class TypedEndpointAdapter

public static class TypedEndpointAdapter

Adapts typed endpoint handlers to the raw endpoint interface.

Members

MemberKindSummary
Adapt(IRawStellaEndpoint)methodCreates a raw handler function from a raw endpoint.
Adapt<TRequest, TResponse>(IStellaEndpoint<TRequest, TResponse>, JsonSerializerOptions)methodCreates a raw handler function from a typed endpoint with request and response.
Adapt<TResponse>(IStellaEndpoint<TResponse>, JsonSerializerOptions)methodCreates a raw handler function from a typed endpoint with response only.

method Adapt(IRawStellaEndpoint) #

public static Func<RawRequestContext, CancellationToken, Task<RawResponse>> Adapt(IRawStellaEndpoint handler)

Creates a raw handler function from a raw endpoint.

Parameters

  • handler: The raw handler.

Returns

A raw handler function.

method Adapt<TRequest, TResponse>(IStellaEndpoint<TRequest, TResponse>, JsonSerializerOptions) #

public static Func<RawRequestContext, CancellationToken, Task<RawResponse>> Adapt<TRequest, TResponse>(IStellaEndpoint<TRequest, TResponse> handler, JsonSerializerOptions? jsonOptions = null)

Creates a raw handler function from a typed endpoint with request and response.

Type parameters

  • TRequest: The request type.
  • TResponse: The response type.

Parameters

  • handler: The typed handler.
  • jsonOptions: Optional JSON serialization options.

Returns

A raw handler function.

method Adapt<TResponse>(IStellaEndpoint<TResponse>, JsonSerializerOptions) #

public static Func<RawRequestContext, CancellationToken, Task<RawResponse>> Adapt<TResponse>(IStellaEndpoint<TResponse> handler, JsonSerializerOptions? jsonOptions = null)

Creates a raw handler function from a typed endpoint with response only.

Type parameters

  • TResponse: The response type.

Parameters

  • handler: The typed handler.
  • jsonOptions: Optional JSON serialization options.

Returns

A raw handler function.

class ValidateSchemaAttribute

public sealed class ValidateSchemaAttribute : Attribute

Enables JSON Schema validation for this endpoint. Schemas are generated from TRequest/TResponse types at compile time.

Applies to: Class. Allow multiple: no. Inherited: no.

Remarks

When applied to an endpoint class that implements IStellaEndpoint<TRequest, TResponse>, the source generator will generate a JSON Schema from the request type and validate all incoming requests against it. Invalid requests receive a 422 Unprocessable Entity response with detailed errors.

Response validation is opt-in via ValidateSchemaAttribute.ValidateResponse. This is useful for catching bugs in handlers but adds overhead.

Example

// Basic usage - validates request only
[StellaEndpoint("POST", "/invoices")]
[ValidateSchema]
public sealed class CreateInvoiceEndpoint : IStellaEndpoint<CreateInvoiceRequest, CreateInvoiceResponse>

// With response validation
[StellaEndpoint("GET", "/invoices/{id}")]
[ValidateSchema(ValidateResponse = true)]
public sealed class GetInvoiceEndpoint : IStellaEndpoint<GetInvoiceRequest, GetInvoiceResponse>

Members

MemberKindSummary
ValidateSchemaAttribute()constructorCreates an instance of ValidateSchemaAttribute.
DeprecatedpropertyGets or sets whether this endpoint is deprecated.
DescriptionpropertyGets or sets the OpenAPI operation description.
SummarypropertyGets or sets the OpenAPI operation summary.
TagspropertyGets or sets the OpenAPI tags for this endpoint.
ValidateRequestpropertyGets or sets whether to validate request bodies.
ValidateResponsepropertyGets or sets whether to validate response bodies.

constructor ValidateSchemaAttribute() #

public ValidateSchemaAttribute()

Creates an instance of ValidateSchemaAttribute.

property Deprecated #

public bool Deprecated { get; set; }

Gets or sets whether this endpoint is deprecated. Deprecated endpoints are marked as such in OpenAPI documentation.

property Description #

public string? Description { get; set; }

Gets or sets the OpenAPI operation description. A longer description of the endpoint’s behavior.

property Summary #

public string? Summary { get; set; }

Gets or sets the OpenAPI operation summary. A brief description of what the endpoint does.

property Tags #

public string[]? Tags { get; set; }

Gets or sets the OpenAPI tags for this endpoint. Tags are used to group endpoints in documentation.

property ValidateRequest #

public bool ValidateRequest { get; set; }

Gets or sets whether to validate request bodies. Default is true.

property ValidateResponse #

public bool ValidateResponse { get; set; }

Gets or sets whether to validate response bodies. Default is false. Enable for debugging or strict contract enforcement: a typed response that fails the schema generated from TResponse is logged and answered with a generic 500.

namespace StellaOps.Microservice.Endpoints

TypeKindDescription
EndpointSchemaInforecordInformation about an endpoint’s schema availability.
SchemaDetailEndpointclassEndpoint that returns a specific schema as application/schema+json.
SchemaIndexEndpointclassEndpoint that returns an index of all available schemas.
SchemaIndexResponserecordResponse model for the schema index endpoint.

record EndpointSchemaInfo

public sealed record EndpointSchemaInfo

Information about an endpoint’s schema availability.

Members

MemberKindSummary
EndpointSchemaInfo()constructorCreates an instance of EndpointSchemaInfo.
HasRequestSchemapropertyWhether a request schema is available.
HasResponseSchemapropertyWhether a response schema is available.
MethodpropertyThe HTTP method.
PathpropertyThe endpoint path.
RequestSchemaUrlpropertyLink to fetch the request schema.
ResponseSchemaUrlpropertyLink to fetch the response schema.

constructor EndpointSchemaInfo() #

public EndpointSchemaInfo()

Creates an instance of EndpointSchemaInfo.

property HasRequestSchema #

public bool HasRequestSchema { get; init; }

Whether a request schema is available.

property HasResponseSchema #

public bool HasResponseSchema { get; init; }

Whether a response schema is available.

property Method #

public required string Method { get; init; }

The HTTP method.

property Path #

public required string Path { get; init; }

The endpoint path.

property RequestSchemaUrl #

public string? RequestSchemaUrl { get; init; }

Link to fetch the request schema.

property ResponseSchemaUrl #

public string? ResponseSchemaUrl { get; init; }

Link to fetch the response schema.

class SchemaDetailEndpoint

public sealed class SchemaDetailEndpoint : IRawStellaEndpoint

Endpoint that returns a specific schema as application/schema+json. Supports ETag and If-None-Match for caching.

Members

MemberKindSummary
SchemaDetailEndpoint(ISchemaRegistry)constructorInitializes a new instance of the SchemaDetailEndpointclass.
HandleAsync(RawRequestContext, CancellationToken)methodHandles the raw request with full context.

constructor SchemaDetailEndpoint(ISchemaRegistry) #

public SchemaDetailEndpoint(ISchemaRegistry schemaRegistry)

Initializes a new instance of the SchemaDetailEndpointclass.

Parameters

  • schemaRegistry: The schema registry.

method HandleAsync(RawRequestContext, CancellationToken) #

public Task<RawResponse> HandleAsync(RawRequestContext context, CancellationToken cancellationToken)

Handles the raw request with full context.

Parameters

  • context: The request context including headers, path parameters, and body stream.
  • cancellationToken: Cancellation token.

Returns

The raw response including status code, headers, and body stream.

class SchemaIndexEndpoint

public sealed class SchemaIndexEndpoint : IStellaEndpoint<SchemaIndexResponse>

Endpoint that returns an index of all available schemas.

Members

MemberKindSummary
SchemaIndexEndpoint(ISchemaRegistry)constructorInitializes a new instance of the SchemaIndexEndpointclass.
HandleAsync(CancellationToken)methodHandles the request.

constructor SchemaIndexEndpoint(ISchemaRegistry) #

public SchemaIndexEndpoint(ISchemaRegistry schemaRegistry)

Initializes a new instance of the SchemaIndexEndpointclass.

Parameters

  • schemaRegistry: The schema registry.

method HandleAsync(CancellationToken) #

public Task<SchemaIndexResponse> HandleAsync(CancellationToken cancellationToken)

Handles the request.

Parameters

  • cancellationToken: Cancellation token.

Returns

The response.

record SchemaIndexResponse

public sealed record SchemaIndexResponse

Response model for the schema index endpoint.

Members

MemberKindSummary
SchemaIndexResponse()constructorCreates an instance of SchemaIndexResponse.
EndpointspropertyList of endpoints with schema information.

constructor SchemaIndexResponse() #

public SchemaIndexResponse()

Creates an instance of SchemaIndexResponse.

property Endpoints #

public required IReadOnlyList<EndpointSchemaInfo> Endpoints { get; init; }

List of endpoints with schema information.

namespace StellaOps.Microservice.Streaming

TypeKindDescription
StreamChunkrecordRepresents a chunk of streaming data.
StreamingRequestBodyStreamclassA read-only stream that reads from a channel of data chunks.
StreamingResponseBodyStreamclassA write-only stream that writes chunks to a channel.

record StreamChunk

public sealed record StreamChunk

Represents a chunk of streaming data.

Members

MemberKindSummary
StreamChunk()constructorCreates an instance of StreamChunk.
DatapropertyGets the chunk data.
EndOfStreampropertyGets a value indicating whether this is the final chunk.
SequenceNumberpropertyGets the sequence number.

constructor StreamChunk() #

public StreamChunk()

Creates an instance of StreamChunk.

property Data #

public byte[] Data { get; init; }

Gets the chunk data.

property EndOfStream #

public bool EndOfStream { get; init; }

Gets a value indicating whether this is the final chunk.

property SequenceNumber #

public int SequenceNumber { get; init; }

Gets the sequence number.

class StreamingRequestBodyStream

public sealed class StreamingRequestBodyStream : Stream

A read-only stream that reads from a channel of data chunks. Used to expose streaming request body to handlers.

Members

MemberKindSummary
StreamingRequestBodyStream(ChannelReader<StreamChunk>, CancellationToken)constructorInitializes a new instance of the StreamingRequestBodyStreamclass.
CanReadpropertySee Stream.CanRead.
CanSeekpropertySee Stream.CanSeek.
CanWritepropertySee Stream.CanWrite.
LengthpropertySee Stream.Length.
PositionpropertySee Stream.Position.
Flush()methodSee Stream.Flush().
Read(byte[], int, int)methodSee Stream.Read(byte[], int, int).
ReadAsync(Memory<byte>, CancellationToken)methodSee Stream.ReadAsync(Memory<byte>, CancellationToken).
ReadAsync(byte[], int, int, CancellationToken)methodSee Stream.ReadAsync(byte[], int, int, CancellationToken).
Seek(long, SeekOrigin)methodSee Stream.Seek(long, SeekOrigin).
SetLength(long)methodSee Stream.SetLength(long).
Write(byte[], int, int)methodSee Stream.Write(byte[], int, int).

constructor StreamingRequestBodyStream(ChannelReader<StreamChunk>, CancellationToken) #

public StreamingRequestBodyStream(ChannelReader<StreamChunk> reader, CancellationToken cancellationToken)

Initializes a new instance of the StreamingRequestBodyStreamclass.

Parameters

  • reader: The channel reader for incoming chunks.
  • cancellationToken: Cancellation token.

property CanRead #

public override bool CanRead { get; }

See Stream.CanRead.

property CanSeek #

public override bool CanSeek { get; }

See Stream.CanSeek.

property CanWrite #

public override bool CanWrite { get; }

See Stream.CanWrite.

property Length #

public override long Length { get; }

See Stream.Length.

property Position #

public override long Position { get; set; }

See Stream.Position.

method Flush() #

public override void Flush()

See Stream.Flush().

method Read(byte[], int, int) #

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

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

method ReadAsync(Memory<byte>, CancellationToken) #

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

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

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

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

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

method Seek(long, SeekOrigin) #

public override long Seek(long offset, SeekOrigin origin)

See Stream.Seek(long, SeekOrigin).

method SetLength(long) #

public override void SetLength(long value)

See Stream.SetLength(long).

method Write(byte[], int, int) #

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

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

class StreamingResponseBodyStream

public sealed class StreamingResponseBodyStream : Stream

A write-only stream that writes chunks to a channel. Used to enable streaming response body from handlers.

Members

MemberKindSummary
StreamingResponseBodyStream(ChannelWriter<StreamChunk>, int, CancellationToken)constructorInitializes a new instance of the StreamingResponseBodyStreamclass.
CanReadpropertySee Stream.CanRead.
CanSeekpropertySee Stream.CanSeek.
CanWritepropertySee Stream.CanWrite.
LengthpropertySee Stream.Length.
PositionpropertySee Stream.Position.
CompleteAsync(CancellationToken)methodCompletes the stream by flushing remaining data and sending end-of-stream signal.
DisposeAsync()methodSee Stream.DisposeAsync().
Flush()methodSee Stream.Flush().
FlushAsync(CancellationToken)methodSee Stream.FlushAsync(CancellationToken).
Read(byte[], int, int)methodSee Stream.Read(byte[], int, int).
Seek(long, SeekOrigin)methodSee Stream.Seek(long, SeekOrigin).
SetLength(long)methodSee Stream.SetLength(long).
Write(byte[], int, int)methodSee Stream.Write(byte[], int, int).
WriteAsync(ReadOnlyMemory<byte>, CancellationToken)methodSee Stream.WriteAsync(ReadOnlyMemory<byte>, CancellationToken).
WriteAsync(byte[], int, int, CancellationToken)methodSee Stream.WriteAsync(byte[], int, int, CancellationToken).

constructor StreamingResponseBodyStream(ChannelWriter<StreamChunk>, int, CancellationToken) #

public StreamingResponseBodyStream(ChannelWriter<StreamChunk> writer, int chunkSize, CancellationToken cancellationToken)

Initializes a new instance of the StreamingResponseBodyStreamclass.

Parameters

  • writer: The channel writer for outgoing chunks.
  • chunkSize: The chunk size for buffered writes.
  • cancellationToken: Cancellation token.

property CanRead #

public override bool CanRead { get; }

See Stream.CanRead.

property CanSeek #

public override bool CanSeek { get; }

See Stream.CanSeek.

property CanWrite #

public override bool CanWrite { get; }

See Stream.CanWrite.

property Length #

public override long Length { get; }

See Stream.Length.

property Position #

public override long Position { get; set; }

See Stream.Position.

method CompleteAsync(CancellationToken) #

public Task CompleteAsync(CancellationToken cancellationToken = default)

Completes the stream by flushing remaining data and sending end-of-stream signal.

method DisposeAsync() #

public override ValueTask DisposeAsync()

See Stream.DisposeAsync().

method Flush() #

public override void Flush()

See Stream.Flush().

method FlushAsync(CancellationToken) #

public override Task FlushAsync(CancellationToken cancellationToken)

See Stream.FlushAsync(CancellationToken).

method Read(byte[], int, int) #

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

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

method Seek(long, SeekOrigin) #

public override long Seek(long offset, SeekOrigin origin)

See Stream.Seek(long, SeekOrigin).

method SetLength(long) #

public override void SetLength(long value)

See Stream.SetLength(long).

method Write(byte[], int, int) #

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

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

method WriteAsync(ReadOnlyMemory<byte>, CancellationToken) #

public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)

See Stream.WriteAsync(ReadOnlyMemory<byte>, CancellationToken).

method WriteAsync(byte[], int, int, CancellationToken) #

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)

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

namespace StellaOps.Microservice.Validation

TypeKindDescription
EndpointSchemaDefinitionrecordDefines the schema information for an endpoint.
IGeneratedSchemaProviderinterfaceInterface implemented by the source-generated schema provider.
IRequestSchemaValidatorinterfaceValidates JSON documents against JSON schemas.
ISchemaRegistryinterfaceRegistry for JSON schemas associated with endpoints.
RequestSchemaValidatorclassValidates JSON documents against JSON schemas using JsonSchema.Net.
SchemaDirectionenumSpecifies the direction of schema validation.
SchemaRegistryclassRegistry for JSON schemas with caching and ETag support.
SchemaValidationErrorrecordRepresents a single schema validation error.
SchemaValidationExceptionclassException thrown when request or response body fails schema validation.
ValidationProblemDetailsclassRFC 7807 Problem Details for schema validation failures.

record EndpointSchemaDefinition

public sealed record EndpointSchemaDefinition

Defines the schema information for an endpoint. Generated at compile time by the source generator.

Parameters

  • Method: The HTTP method (GET, POST, etc.).
  • Path: The endpoint path template.
  • RequestSchemaJson: The JSON Schema for the request body, or null if not validated.
  • ResponseSchemaJson: The JSON Schema for the response body, or null if not validated.
  • ValidateRequest: Whether request validation is enabled.
  • ValidateResponse: Whether response validation is enabled.

Members

MemberKindSummary
EndpointSchemaDefinition(string, string, string, string, bool, bool)constructorDefines the schema information for an endpoint.
MethodpropertyThe HTTP method (GET, POST, etc.).
PathpropertyThe endpoint path template.
RequestSchemaJsonpropertyThe JSON Schema for the request body, or null if not validated.
ResponseSchemaJsonpropertyThe JSON Schema for the response body, or null if not validated.
ValidateRequestpropertyWhether request validation is enabled.
ValidateResponsepropertyWhether response validation is enabled.

constructor EndpointSchemaDefinition(string, string, string, string, bool, bool) #

public EndpointSchemaDefinition(string Method, string Path, string? RequestSchemaJson, string? ResponseSchemaJson, bool ValidateRequest, bool ValidateResponse)

Defines the schema information for an endpoint. Generated at compile time by the source generator.

Parameters

  • Method: The HTTP method (GET, POST, etc.).
  • Path: The endpoint path template.
  • RequestSchemaJson: The JSON Schema for the request body, or null if not validated.
  • ResponseSchemaJson: The JSON Schema for the response body, or null if not validated.
  • ValidateRequest: Whether request validation is enabled.
  • ValidateResponse: Whether response validation is enabled.

property Method #

public string Method { get; init; }

The HTTP method (GET, POST, etc.).

property Path #

public string Path { get; init; }

The endpoint path template.

property RequestSchemaJson #

public string? RequestSchemaJson { get; init; }

The JSON Schema for the request body, or null if not validated.

property ResponseSchemaJson #

public string? ResponseSchemaJson { get; init; }

The JSON Schema for the response body, or null if not validated.

property ValidateRequest #

public bool ValidateRequest { get; init; }

Whether request validation is enabled.

property ValidateResponse #

public bool ValidateResponse { get; init; }

Whether response validation is enabled.

interface IGeneratedSchemaProvider

public interface IGeneratedSchemaProvider

Interface implemented by the source-generated schema provider. Provides access to schemas generated at compile time.

Members

MemberKindSummary
GetSchemaDefinitions()methodGets all endpoint schema definitions generated at compile time.

method GetSchemaDefinitions() #

IReadOnlyList<EndpointSchemaDefinition> GetSchemaDefinitions()

Gets all endpoint schema definitions generated at compile time.

Returns

A list of all endpoint schema definitions.

interface IRequestSchemaValidator

public interface IRequestSchemaValidator

Validates JSON documents against JSON schemas.

Members

MemberKindSummary
TryValidate(JsonDocument, JsonSchema, out IReadOnlyList<SchemaValidationError>)methodValidates a JSON document against a schema.

method TryValidate(JsonDocument, JsonSchema, out IReadOnlyList<SchemaValidationError>) #

bool TryValidate(JsonDocument document, JsonSchema schema, out IReadOnlyList<SchemaValidationError> errors)

Validates a JSON document against a schema.

Parameters

  • document: The JSON document to validate.
  • schema: The JSON schema to validate against.
  • errors: When validation fails, contains the list of errors.

Returns

True if the document is valid, false otherwise.

interface ISchemaRegistry

public interface ISchemaRegistry

Registry for JSON schemas associated with endpoints. Provides compiled schemas for validation and raw text for documentation.

Members

MemberKindSummary
GetAllSchemas()methodGets all registered schema definitions.
GetRequestSchema(string, string)methodGets the compiled JSON schema for an endpoint’s request.
GetResponseSchema(string, string)methodGets the compiled JSON schema for an endpoint’s response.
GetSchemaETag(string, string, SchemaDirection)methodGets the ETag for the schema (for HTTP caching).
GetSchemaText(string, string, SchemaDirection)methodGets the raw schema text for documentation/publication.
HasSchema(string, string, SchemaDirection)methodChecks if an endpoint has a schema registered.

method GetAllSchemas() #

IReadOnlyList<EndpointSchemaDefinition> GetAllSchemas()

Gets all registered schema definitions.

Returns

All endpoint schema definitions.

method GetRequestSchema(string, string) #

JsonSchema? GetRequestSchema(string method, string path)

Gets the compiled JSON schema for an endpoint’s request.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.

Returns

The compiled schema, or null if no schema is registered.

method GetResponseSchema(string, string) #

JsonSchema? GetResponseSchema(string method, string path)

Gets the compiled JSON schema for an endpoint’s response.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.

Returns

The compiled schema, or null if no schema is registered.

method GetSchemaETag(string, string, SchemaDirection) #

string? GetSchemaETag(string method, string path, SchemaDirection direction)

Gets the ETag for the schema (for HTTP caching).

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.
  • direction: Whether to get request or response schema.

Returns

The ETag value, or null if no schema is registered.

method GetSchemaText(string, string, SchemaDirection) #

string? GetSchemaText(string method, string path, SchemaDirection direction)

Gets the raw schema text for documentation/publication.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.
  • direction: Whether to get request or response schema.

Returns

The raw JSON schema text, or null if no schema is registered.

method HasSchema(string, string, SchemaDirection) #

bool HasSchema(string method, string path, SchemaDirection direction)

Checks if an endpoint has a schema registered.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.
  • direction: Whether to check request or response schema.

Returns

True if a schema is registered.

class RequestSchemaValidator

public sealed class RequestSchemaValidator : IRequestSchemaValidator

Validates JSON documents against JSON schemas using JsonSchema.Net.

Members

MemberKindSummary
RequestSchemaValidator(ILogger<RequestSchemaValidator>)constructorCreates a new request schema validator.
TryValidate(JsonDocument, JsonSchema, out IReadOnlyList<SchemaValidationError>)methodValidates a JSON document against a schema.

constructor RequestSchemaValidator(ILogger<RequestSchemaValidator>) #

public RequestSchemaValidator(ILogger<RequestSchemaValidator> logger)

Creates a new request schema validator.

method TryValidate(JsonDocument, JsonSchema, out IReadOnlyList<SchemaValidationError>) #

public bool TryValidate(JsonDocument document, JsonSchema schema, out IReadOnlyList<SchemaValidationError> errors)

Validates a JSON document against a schema.

Parameters

  • document: The JSON document to validate.
  • schema: The JSON schema to validate against.
  • errors: When validation fails, contains the list of errors.

Returns

True if the document is valid, false otherwise.

enum SchemaDirection

public enum SchemaDirection

Specifies the direction of schema validation.

ValueDescription
Request = 0Validates incoming request bodies.
Response = 1Validates outgoing response bodies.

class SchemaRegistry

public sealed class SchemaRegistry : ISchemaRegistry

Registry for JSON schemas with caching and ETag support. Follows the RiskProfileSchemaProvider pattern.

Members

MemberKindSummary
SchemaRegistry(ILogger<SchemaRegistry>, IGeneratedSchemaProvider)constructorCreates a new schema registry.
GetAllSchemas()methodGets all registered schema definitions.
GetRequestSchema(string, string)methodGets the compiled JSON schema for an endpoint’s request.
GetResponseSchema(string, string)methodGets the compiled JSON schema for an endpoint’s response.
GetSchemaETag(string, string, SchemaDirection)methodGets the ETag for the schema (for HTTP caching).
GetSchemaText(string, string, SchemaDirection)methodGets the raw schema text for documentation/publication.
HasSchema(string, string, SchemaDirection)methodChecks if an endpoint has a schema registered.

constructor SchemaRegistry(ILogger<SchemaRegistry>, IGeneratedSchemaProvider) #

public SchemaRegistry(ILogger<SchemaRegistry> logger, IGeneratedSchemaProvider? generatedProvider = null)

Creates a new schema registry.

Parameters

  • logger: The logger.
  • generatedProvider: The source-generated schema provider, if available.

method GetAllSchemas() #

public IReadOnlyList<EndpointSchemaDefinition> GetAllSchemas()

Gets all registered schema definitions.

Returns

All endpoint schema definitions.

method GetRequestSchema(string, string) #

public JsonSchema? GetRequestSchema(string method, string path)

Gets the compiled JSON schema for an endpoint’s request.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.

Returns

The compiled schema, or null if no schema is registered.

method GetResponseSchema(string, string) #

public JsonSchema? GetResponseSchema(string method, string path)

Gets the compiled JSON schema for an endpoint’s response.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.

Returns

The compiled schema, or null if no schema is registered.

method GetSchemaETag(string, string, SchemaDirection) #

public string? GetSchemaETag(string method, string path, SchemaDirection direction)

Gets the ETag for the schema (for HTTP caching).

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.
  • direction: Whether to get request or response schema.

Returns

The ETag value, or null if no schema is registered.

method GetSchemaText(string, string, SchemaDirection) #

public string? GetSchemaText(string method, string path, SchemaDirection direction)

Gets the raw schema text for documentation/publication.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.
  • direction: Whether to get request or response schema.

Returns

The raw JSON schema text, or null if no schema is registered.

method HasSchema(string, string, SchemaDirection) #

public bool HasSchema(string method, string path, SchemaDirection direction)

Checks if an endpoint has a schema registered.

Parameters

  • method: The HTTP method.
  • path: The endpoint path template.
  • direction: Whether to check request or response schema.

Returns

True if a schema is registered.

record SchemaValidationError

public sealed record SchemaValidationError

Represents a single schema validation error.

Parameters

  • InstanceLocation: JSON pointer to the invalid value (e.g., “/amount”).
  • SchemaLocation: JSON pointer to the schema constraint (e.g., “#/properties/amount/minimum”).
  • Message: Human-readable error message.
  • Keyword: The JSON Schema keyword that failed (e.g., “required”, “minimum”, “type”).

Members

MemberKindSummary
SchemaValidationError(string, string, string, string)constructorRepresents a single schema validation error.
InstanceLocationpropertyJSON pointer to the invalid value (e.g., “/amount”).
KeywordpropertyThe JSON Schema keyword that failed (e.g., “required”, “minimum”, “type”).
MessagepropertyHuman-readable error message.
SchemaLocationpropertyJSON pointer to the schema constraint (e.g., “#/properties/amount/minimum”).

constructor SchemaValidationError(string, string, string, string) #

public SchemaValidationError(string InstanceLocation, string SchemaLocation, string Message, string Keyword)

Represents a single schema validation error.

Parameters

  • InstanceLocation: JSON pointer to the invalid value (e.g., “/amount”).
  • SchemaLocation: JSON pointer to the schema constraint (e.g., “#/properties/amount/minimum”).
  • Message: Human-readable error message.
  • Keyword: The JSON Schema keyword that failed (e.g., “required”, “minimum”, “type”).

property InstanceLocation #

public string InstanceLocation { get; init; }

JSON pointer to the invalid value (e.g., “/amount”).

property Keyword #

public string Keyword { get; init; }

The JSON Schema keyword that failed (e.g., “required”, “minimum”, “type”).

property Message #

public string Message { get; init; }

Human-readable error message.

property SchemaLocation #

public string SchemaLocation { get; init; }

JSON pointer to the schema constraint (e.g., “#/properties/amount/minimum”).

class SchemaValidationException

public sealed class SchemaValidationException : Exception

Exception thrown when request or response body fails schema validation.

Members

MemberKindSummary
SchemaValidationException(string, string, SchemaDirection, IReadOnlyList<SchemaValidationError>)constructorCreates a new schema validation exception.
DirectionpropertyGets whether this was request or response validation.
EndpointMethodpropertyGets the HTTP method of the endpoint.
EndpointPathpropertyGets the endpoint path where validation failed.
ErrorspropertyGets the list of validation errors.

constructor SchemaValidationException(string, string, SchemaDirection, IReadOnlyList<SchemaValidationError>) #

public SchemaValidationException(string endpointMethod, string endpointPath, SchemaDirection direction, IReadOnlyList<SchemaValidationError> errors)

Creates a new schema validation exception.

property Direction #

public SchemaDirection Direction { get; }

Gets whether this was request or response validation.

property EndpointMethod #

public string EndpointMethod { get; }

Gets the HTTP method of the endpoint.

property EndpointPath #

public string EndpointPath { get; }

Gets the endpoint path where validation failed.

property Errors #

public IReadOnlyList<SchemaValidationError> Errors { get; }

Gets the list of validation errors.

class ValidationProblemDetails

public sealed class ValidationProblemDetails

RFC 7807 Problem Details for schema validation failures. Returns HTTP 422 Unprocessable Entity.

Members

MemberKindSummary
ValidationProblemDetails()constructorCreates an instance of ValidationProblemDetails.
SchemaValidationTypeconstantThe problem type of a schema validation failure: a URN tied to no domain, like every Router problem type (urn:stellaops:router:...).
DetailpropertyA human-readable explanation specific to this occurrence.
ErrorspropertyThe list of validation errors.
InstancepropertyA URI reference identifying the specific occurrence (the endpoint path).
StatuspropertyThe HTTP status code (422).
TitlepropertyA short, human-readable summary of the problem.
TraceIdpropertyThe trace/correlation ID for distributed tracing.
TypepropertyA URI reference identifying the problem type.
Create(string, string, SchemaDirection, IReadOnlyList<SchemaValidationError>, string)methodCreates a ValidationProblemDetails for schema validation failures.
ToRawResponse()methodConverts this problem details to a RawResponse.

constructor ValidationProblemDetails() #

public ValidationProblemDetails()

Creates an instance of ValidationProblemDetails.

constant SchemaValidationType #

public const string SchemaValidationType = "urn:stellaops:router:schema-validation"

The problem type of a schema validation failure: a URN tied to no domain, like every Router problem type (urn:stellaops:router:...).

property Detail #

public string? Detail { get; init; }

A human-readable explanation specific to this occurrence.

property Errors #

public IReadOnlyList<SchemaValidationError> Errors { get; init; }

The list of validation errors.

property Instance #

public string? Instance { get; init; }

A URI reference identifying the specific occurrence (the endpoint path).

property Status #

public int Status { get; init; }

The HTTP status code (422).

property Title #

public string Title { get; init; }

A short, human-readable summary of the problem.

property TraceId #

public string? TraceId { get; init; }

The trace/correlation ID for distributed tracing.

property Type #

public string Type { get; init; }

A URI reference identifying the problem type.

method Create(string, string, SchemaDirection, IReadOnlyList<SchemaValidationError>, string) #

public static ValidationProblemDetails Create(string method, string path, SchemaDirection direction, IReadOnlyList<SchemaValidationError> errors, string? correlationId = null)

Creates a ValidationProblemDetails for schema validation failures.

Parameters

  • method: The HTTP method.
  • path: The endpoint path.
  • direction: Request or response validation.
  • errors: The validation errors.
  • correlationId: Optional correlation ID.

method ToRawResponse() #

public RawResponse ToRawResponse()

Converts this problem details to a RawResponse.