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.

PackageStellaOps.Microservice
ComponentRouter
LicenceApache-2.0
Package kindLibrary
Target frameworknet10.0

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

Namespaces

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

StellaOps.Microservice namespace

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.

ClaimRequirementConfig class

public sealed class ClaimRequirementConfig

Configuration for a claim requirement.

ClaimRequirementConfig() constructor

public ClaimRequirementConfig()

Creates an instance of ClaimRequirementConfig.

Type property

public string Type { get; set; }

Gets or sets the claim type.

Value property

public string? Value { get; set; }

Gets or sets the claim value.

ToClaimRequirement() method

public ClaimRequirement ToClaimRequirement()

Converts to a ClaimRequirement model.

EndpointDiscoveryService class

public sealed class EndpointDiscoveryService : IEndpointDiscoveryService

Service that discovers endpoints and applies YAML configuration overrides.

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

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

Initializes a new instance of the EndpointDiscoveryServiceclass.

DiscoverEndpoints() method

public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints, applying any YAML configuration overrides.

Returns

The discovered endpoints with overrides applied.

EndpointMatch class

public sealed class EndpointMatch

Represents a matched endpoint with extracted path parameters.

EndpointMatch() constructor

public EndpointMatch()

Creates an instance of EndpointMatch.

Endpoint property

public required EndpointDescriptor Endpoint { get; init; }

Gets the matched endpoint descriptor.

PathParameters property

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

Gets the path parameters extracted from the URL.

EndpointOverrideConfig class

public sealed class EndpointOverrideConfig

Configuration for overriding an endpoint’s properties.

EndpointOverrideConfig() constructor

public EndpointOverrideConfig()

Creates an instance of EndpointOverrideConfig.

DefaultTimeout property

public string? DefaultTimeout { get; set; }

Gets or sets the default timeout override.

Method property

public string Method { get; set; }

Gets or sets the HTTP method to match.

Path property

public string Path { get; set; }

Gets or sets the path to match.

RequiringClaims property

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

Gets or sets the claim requirements.

SupportsStreaming property

public bool? SupportsStreaming { get; set; }

Gets or sets whether streaming is supported.

GetDefaultTimeoutAsTimeSpan() method

public TimeSpan? GetDefaultTimeoutAsTimeSpan()

Parses the DefaultTimeout string to a TimeSpan.

TryGetDefaultTimeoutAsTimeSpan(out TimeSpan, out string) method

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

Parses the DefaultTimeout string to a TimeSpan with error output.

EndpointOverrideMerger class

public sealed class EndpointOverrideMerger : IEndpointOverrideMerger

Merges endpoint overrides from YAML configuration with code defaults.

EndpointOverrideMerger(ILogger<EndpointOverrideMerger>) constructor

public EndpointOverrideMerger(ILogger<EndpointOverrideMerger> logger)

Initializes a new instance of the EndpointOverrideMergerclass.

Merge(IReadOnlyList<EndpointDescriptor>, MicroserviceYamlConfig) method

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

Merges YAML overrides with code-defined endpoints.

Parameters

Returns

The merged endpoints.

EndpointRegistry class

public sealed class EndpointRegistry : IEndpointRegistry

Default implementation of endpoint registry using path matchers.

EndpointRegistry(bool) constructor

public EndpointRegistry(bool caseInsensitive = true)

Initializes a new instance of the EndpointRegistryclass.

Parameters

GetAllEndpoints() method

public IReadOnlyList<EndpointDescriptor> GetAllEndpoints()

Gets all registered endpoints.

Returns

All registered endpoint descriptors.

Register(EndpointDescriptor) method

public void Register(EndpointDescriptor endpoint)

Registers an endpoint descriptor.

Parameters

RegisterAll(IEnumerable<EndpointDescriptor>) method

public void RegisterAll(IEnumerable<EndpointDescriptor> endpoints)

Registers multiple endpoint descriptors.

Parameters

TryMatch(string, string, out EndpointMatch) method

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

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

Parameters

Returns

True if a matching endpoint was found.

GeneratedEndpointDiscoveryProvider class

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.

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

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

Initializes a new instance of the GeneratedEndpointDiscoveryProviderclass.

DiscoverEndpoints() method

public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints in the application.

Returns

The discovered endpoints.

DiscoverSchemaDefinitions() method

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

HeaderCollection class

public sealed class HeaderCollection : IHeaderCollection

Default implementation of header collection.

HeaderCollection() constructor

public HeaderCollection()

Initializes a new instance of the HeaderCollectionclass.

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

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

Initializes a new instance from key-value pairs.

Empty field

public static readonly HeaderCollection Empty

Gets an empty header collection.

this[string] indexer

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

Gets a header value by key.

Parameters

Returns

The header value, or null if not found.

Add(string, string) method

public void Add(string key, string value)

Adds a header value.

Parameters

ContainsKey(string) method

public bool ContainsKey(string key)

Checks if a header exists.

Parameters

Returns

True if the header exists.

GetEnumerator() method

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

See IEnumerable<T>.GetEnumerator().

GetValues(string) method

public IEnumerable<string> GetValues(string key)

Gets all values for a header key.

Parameters

Returns

All values for the key.

Set(string, string) method

public void Set(string key, string value)

Sets a header, replacing any existing values.

Parameters

TryGetValue(string, out string) method

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

Tries to get a header value.

Parameters

Returns

True if the header was found.

IEndpointDiscoveryProvider interface

public interface IEndpointDiscoveryProvider

Provides endpoint discovery functionality.

DiscoverEndpoints() method

IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints in the application.

Returns

The discovered endpoints.

IEndpointDiscoveryService interface

public interface IEndpointDiscoveryService

Interface for discovering endpoints with YAML configuration support.

DiscoverEndpoints() method

IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints, applying any YAML configuration overrides.

Returns

The discovered endpoints with overrides applied.

IEndpointOverrideMerger interface

public interface IEndpointOverrideMerger

Interface for merging endpoint overrides from YAML configuration.

Merge(IReadOnlyList<EndpointDescriptor>, MicroserviceYamlConfig) method

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

Merges YAML overrides with code-defined endpoints.

Parameters

Returns

The merged endpoints.

IEndpointRegistry interface

public interface IEndpointRegistry

Registry for looking up endpoint handlers by method and path.

GetAllEndpoints() method

IReadOnlyList<EndpointDescriptor> GetAllEndpoints()

Gets all registered endpoints.

Returns

All registered endpoint descriptors.

TryMatch(string, string, out EndpointMatch) method

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

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

Parameters

Returns

True if a matching endpoint was found.

IEndpointSchemaDefinitionProvider interface

public interface IEndpointSchemaDefinitionProvider

Optional provider for endpoint JSON schema definitions discovered at runtime.

DiscoverSchemaDefinitions() method

IReadOnlyDictionary<string, SchemaDefinition> DiscoverSchemaDefinitions()

Gets schema definitions keyed by schema identifier.

IGeneratedEndpointProvider interface

public interface IGeneratedEndpointProvider

Interface implemented by the source-generated endpoint provider.

GetEndpoints() method

IReadOnlyList<EndpointDescriptor> GetEndpoints()

Gets all discovered endpoint descriptors.

GetHandlerTypes() method

IReadOnlyList<Type> GetHandlerTypes()

Gets all handler types for endpoint discovery.

GetSchemaDefinitions() method

IReadOnlyDictionary<string, SchemaDefinition> GetSchemaDefinitions()

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

RegisterHandlers(IServiceCollection) method

void RegisterHandlers(IServiceCollection services)

Registers all endpoint handlers with the service collection.

IHeaderCollection interface

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

Abstraction for HTTP-style header collection.

this[string] indexer

string? this[string key] { get; }

Gets a header value by key.

Parameters

Returns

The header value, or null if not found.

ContainsKey(string) method

bool ContainsKey(string key)

Checks if a header exists.

Parameters

Returns

True if the header exists.

GetValues(string) method

IEnumerable<string> GetValues(string key)

Gets all values for a header key.

Parameters

Returns

All values for the key.

TryGetValue(string, out string) method

bool TryGetValue(string key, out string? value)

Tries to get a header value.

Parameters

Returns

True if the header was found.

IMicroserviceYamlLoader interface

public interface IMicroserviceYamlLoader

Interface for loading microservice YAML configuration.

Load() method

MicroserviceYamlConfig? Load()

Loads the microservice configuration from YAML.

Returns

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

IRawStellaEndpoint interface

public interface IRawStellaEndpoint : IStellaEndpoint

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

HandleAsync(RawRequestContext, CancellationToken) method

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

Handles the raw request with full context.

Parameters

Returns

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

IRequestDispatcher interface

public interface IRequestDispatcher

Abstraction for dispatching Router request frames to handlers.

CanHandle(string, string) method

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

Returns

True if this dispatcher can handle the request.

DispatchAsync(RequestFrame, CancellationToken) method

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

Dispatches a REQUEST frame and returns a RESPONSE frame.

Parameters

Returns

The RESPONSE frame.

IRouterConnectionManager interface

public interface IRouterConnectionManager

Manages connections to router gateways.

Connections property

IReadOnlyList<ConnectionState> Connections { get; }

Gets the current connection states.

InFlightRequestCount property

int InFlightRequestCount { get; }

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

BeginDrainAsync(CancellationToken) method

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

SendGoodbyeAsync(CancellationToken) method

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

StartAsync(CancellationToken) method

Task StartAsync(CancellationToken cancellationToken)

Starts the connection manager.

Parameters

StopAsync(CancellationToken) method

Task StopAsync(CancellationToken cancellationToken)

Stops the connection manager.

Parameters

IStellaEndpoint interface

public interface IStellaEndpoint

Marker interface for all Stella endpoints.

IStellaEndpoint<TRequest, TResponse> interface

public interface IStellaEndpoint<TRequest, TResponse> : IStellaEndpoint

Interface for a typed Stella endpoint with request and response.

Type parameters

HandleAsync(TRequest, CancellationToken) method

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

Handles the request.

Parameters

Returns

The response.

IStellaEndpoint<TResponse> interface

public interface IStellaEndpoint<TResponse> : IStellaEndpoint

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

Type parameters

HandleAsync(CancellationToken) method

Task<TResponse> HandleAsync(CancellationToken cancellationToken)

Handles the request.

Parameters

Returns

The response.

InflightRequestTracker class

public sealed class InflightRequestTracker : IDisposable

Tracks in-flight requests and manages their cancellation tokens.

InflightRequestTracker(ILogger<InflightRequestTracker>) constructor

public InflightRequestTracker(ILogger<InflightRequestTracker> logger)

Initializes a new instance of the InflightRequestTrackerclass.

Count property

public int Count { get; }

Gets the count of in-flight requests.

Cancel(Guid, string) method

public bool Cancel(Guid correlationId, string? reason)

Cancels a specific request.

Parameters

Returns

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

CancelAll(string) method

public void CancelAll(string reason)

Cancels all in-flight requests.

Parameters

Complete(Guid) method

public void Complete(Guid correlationId)

Marks a request as completed and removes it from tracking.

Parameters

Dispose() method

public void Dispose()

See IDisposable.Dispose().

Track(Guid) method

public CancellationToken Track(Guid correlationId)

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

Parameters

Returns

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

MicroserviceHostedService class

public sealed class MicroserviceHostedService : IHostedService, IDisposable

Hosted service that manages the microservice lifecycle.

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

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

Initializes a new instance of the MicroserviceHostedServiceclass.

Dispose() method

public void Dispose()

See IDisposable.Dispose().

StartAsync(CancellationToken) method

public Task StartAsync(CancellationToken cancellationToken)

See IHostedService.StartAsync(CancellationToken).

StopAsync(CancellationToken) method

public Task StopAsync(CancellationToken cancellationToken)

See IHostedService.StopAsync(CancellationToken).

MicroserviceServiceCollectionExtensions class

public static class MicroserviceServiceCollectionExtensions

Extension methods for registering Stella microservice services.

AddStellaEndpoint<THandler>(IServiceCollection) extension method

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

Registers an endpoint handler type for dependency injection.

Type parameters

Parameters

Returns

The service collection for chaining.

AddStellaMicroservice(IServiceCollection, Action<StellaMicroserviceOptions>) extension method

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

Adds Stella microservice services to the service collection.

Parameters

Returns

The service collection for chaining.

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

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

Parameters

Returns

The service collection for chaining.

AddStellaSchemaProvider<TProvider>(IServiceCollection) extension method

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

Registers a generated schema provider for schema validation.

Type parameters

Parameters

Returns

The service collection for chaining.

MicroserviceYamlConfig class

public sealed class MicroserviceYamlConfig

Root configuration for microservice endpoint overrides loaded from YAML.

MicroserviceYamlConfig() constructor

public MicroserviceYamlConfig()

Creates an instance of MicroserviceYamlConfig.

Endpoints property

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

Gets or sets the endpoint override configurations.

MicroserviceYamlLoader class

public sealed class MicroserviceYamlLoader : IMicroserviceYamlLoader

Loads microservice configuration from a YAML file.

MicroserviceYamlLoader(StellaMicroserviceOptions, ILogger<MicroserviceYamlLoader>) constructor

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

Initializes a new instance of the MicroserviceYamlLoaderclass.

Load() method

public MicroserviceYamlConfig? Load()

Loads the microservice configuration from YAML.

Returns

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

RawRequestContext class

public sealed class RawRequestContext

Context for a raw request.

RawRequestContext() constructor

public RawRequestContext()

Creates an instance of RawRequestContext.

Body property

public Stream Body { get; init; }

Gets the request body stream.

CancellationToken property

public CancellationToken CancellationToken { get; init; }

Gets the cancellation token.

CorrelationId property

public string? CorrelationId { get; init; }

Gets the correlation ID for request tracking.

Headers property

public IHeaderCollection Headers { get; init; }

Gets the request headers.

Method property

public string Method { get; init; }

Gets the HTTP method.

Path property

public string Path { get; init; }

Gets the request path.

PathParameters property

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

Gets the path parameters extracted from route templates.

QueryParameters property

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

Gets the query parameters extracted from the request path.

RawResponse class

public sealed class RawResponse

Represents a raw response from an endpoint.

RawResponse() constructor

public RawResponse()

Creates an instance of RawResponse.

Body property

public Stream Body { get; init; }

Gets or sets the response body stream.

Headers property

public IHeaderCollection Headers { get; init; }

Gets or sets the response headers.

StatusCode property

public int StatusCode { get; init; }

Gets or sets the HTTP status code.

BadRequest(string) method

public static RawResponse BadRequest(string? message = null)

Creates a 400 Bad Request response.

Error(int, string) method

public static RawResponse Error(int statusCode, string message)

Creates an error response with a message body.

InternalError(string) method

public static RawResponse InternalError(string? message = null)

Creates a 500 Internal Server Error response.

NoContent() method

public static RawResponse NoContent()

Creates a 204 No Content response.

NotFound(string) method

public static RawResponse NotFound(string? message = null)

Creates a 404 Not Found response.

Ok(Stream) method

public static RawResponse Ok(Stream body)

Creates a 200 OK response with a body.

Ok(byte[]) method

public static RawResponse Ok(byte[] body)

Creates a 200 OK response with a byte array body.

Ok(string) method

public static RawResponse Ok(string body)

Creates a 200 OK response with a string body.

ReflectionEndpointDiscoveryProvider class

public sealed class ReflectionEndpointDiscoveryProvider : IEndpointDiscoveryProvider

Discovers endpoints using runtime reflection.

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

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

Initializes a new instance of the ReflectionEndpointDiscoveryProviderclass.

Parameters

DiscoverEndpoints() method

public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()

Discovers all endpoints in the application.

Returns

The discovered endpoints.

RequestDispatcher class

public sealed class RequestDispatcher : IRequestDispatcher

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

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

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

CanHandle(string, string) method

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

Returns

True if this dispatcher can handle the request.

DispatchAsync(RequestFrame, CancellationToken) method

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

Dispatches a REQUEST frame and returns a RESPONSE frame.

Parameters

Returns

The RESPONSE frame.

RouterConnectionManager class

public sealed class RouterConnectionManager : IRouterConnectionManager, IDisposable

Manages connections to router gateways.

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

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

Connections property

public IReadOnlyList<ConnectionState> Connections { get; }

Gets the current connection states.

CurrentStatus property

public InstanceHealthStatus CurrentStatus { get; set; }

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

ErrorRate property

public double ErrorRate { get; set; }

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

InFlightRequestCount property

public int InFlightRequestCount { get; set; }

Gets or sets the count of in-flight requests.

BeginDrainAsync(CancellationToken) method

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

Dispose() method

public void Dispose()

See IDisposable.Dispose().

SendGoodbyeAsync(CancellationToken) method

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

StartAsync(CancellationToken) method

public Task StartAsync(CancellationToken cancellationToken)

Starts the connection manager.

Parameters

StopAsync(CancellationToken) method

public Task StopAsync(CancellationToken cancellationToken)

Stops the connection manager.

Parameters

RouterEndpointConfig class

public sealed class RouterEndpointConfig

Configuration for a router endpoint.

RouterEndpointConfig() constructor

public RouterEndpointConfig()

Creates an instance of RouterEndpointConfig.

Host property

public required string Host { get; set; }

Gets or sets the router host.

Port property

public required int Port { get; set; }

Gets or sets the router port.

TransportType property

public TransportType TransportType { get; set; }

Gets or sets the transport type to use.

SchemaProviderDiscoveryDiagnostics class

public sealed class SchemaProviderDiscoveryDiagnostics

Captures schema provider discovery issues for startup diagnostics.

SchemaProviderDiscoveryDiagnostics(IReadOnlyList<SchemaProviderDiscoveryIssue>) constructor

public SchemaProviderDiscoveryDiagnostics(IReadOnlyList<SchemaProviderDiscoveryIssue> issues)

Initializes a new instance of the SchemaProviderDiscoveryDiagnosticsclass.

Parameters

Issues property

public IReadOnlyList<SchemaProviderDiscoveryIssue> Issues { get; }

Gets the discovery issues.

SchemaProviderDiscoveryIssue record

public sealed record SchemaProviderDiscoveryIssue

Represents a schema provider discovery issue.

Parameters

SchemaProviderDiscoveryIssue(string, string) constructor

public SchemaProviderDiscoveryIssue(string AssemblyName, string Message)

Represents a schema provider discovery issue.

Parameters

AssemblyName property

public string AssemblyName { get; init; }

The assembly whose schema provider could not be read.

Message property

public string Message { get; init; }

What went wrong.

StellaEndpointAttribute class

public sealed class StellaEndpointAttribute : Attribute

Marks a class as a Stella endpoint handler.

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

StellaEndpointAttribute(string, string) constructor

public StellaEndpointAttribute(string method, string path)

Initializes a new instance of the StellaEndpointAttributeclass.

Parameters

Method property

public string Method { get; }

Gets the HTTP method for this endpoint.

Path property

public string Path { get; }

Gets the path for this endpoint.

RequiredClaims property

public string[] RequiredClaims { get; set; }

Gets or sets the required claim types for this endpoint.

SupportsStreaming property

public bool SupportsStreaming { get; set; }

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

TimeoutSeconds property

public int TimeoutSeconds { get; set; }

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

StellaMicroserviceOptions class

public sealed class StellaMicroserviceOptions

Options for configuring a Stella microservice.

StellaMicroserviceOptions() constructor

public StellaMicroserviceOptions()

Creates an instance of StellaMicroserviceOptions.

ConfigFilePath property

public string? ConfigFilePath { get; set; }

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

ContactInfo property

public string? ContactInfo { get; set; }

Gets or sets the contact information for OpenAPI documentation.

DrainDeadline property

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.

DrainPollInterval property

public TimeSpan DrainPollInterval { get; set; }

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

HeartbeatInterval property

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.

InstanceId property

public string InstanceId { get; set; }

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

ReconnectBackoffInitial property

public TimeSpan ReconnectBackoffInitial { get; set; }

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

ReconnectBackoffMax property

public TimeSpan ReconnectBackoffMax { get; set; }

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

Region property

public required string Region { get; set; }

Gets or sets the region where this instance is deployed.

Routers property

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

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

ServiceDescription property

public string? ServiceDescription { get; set; }

Gets or sets the service description for OpenAPI documentation.

ServiceName property

public required string ServiceName { get; set; }

Gets or sets the service name.

Version property

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

Weight property

public int Weight { get; set; }

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

Validate() method

public void Validate()

Validates the options and throws if invalid.

TypedEndpointAdapter class

public static class TypedEndpointAdapter

Adapts typed endpoint handlers to the raw endpoint interface.

Adapt(IRawStellaEndpoint) method

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

Creates a raw handler function from a raw endpoint.

Parameters

Returns

A raw handler function.

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

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

Parameters

Returns

A raw handler function.

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

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

Parameters

Returns

A raw handler function.

ValidateSchemaAttribute class

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>

ValidateSchemaAttribute() constructor

public ValidateSchemaAttribute()

Creates an instance of ValidateSchemaAttribute.

Deprecated property

public bool Deprecated { get; set; }

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

Description property

public string? Description { get; set; }

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

Summary property

public string? Summary { get; set; }

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

Tags property

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

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

ValidateRequest property

public bool ValidateRequest { get; set; }

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

ValidateResponse property

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.

StellaOps.Microservice.Endpoints namespace

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.

EndpointSchemaInfo record

public sealed record EndpointSchemaInfo

Information about an endpoint’s schema availability.

EndpointSchemaInfo() constructor

public EndpointSchemaInfo()

Creates an instance of EndpointSchemaInfo.

HasRequestSchema property

public bool HasRequestSchema { get; init; }

Whether a request schema is available.

HasResponseSchema property

public bool HasResponseSchema { get; init; }

Whether a response schema is available.

Method property

public required string Method { get; init; }

The HTTP method.

Path property

public required string Path { get; init; }

The endpoint path.

RequestSchemaUrl property

public string? RequestSchemaUrl { get; init; }

Link to fetch the request schema.

ResponseSchemaUrl property

public string? ResponseSchemaUrl { get; init; }

Link to fetch the response schema.

SchemaDetailEndpoint class

public sealed class SchemaDetailEndpoint : IRawStellaEndpoint

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

SchemaDetailEndpoint(ISchemaRegistry) constructor

public SchemaDetailEndpoint(ISchemaRegistry schemaRegistry)

Initializes a new instance of the SchemaDetailEndpointclass.

Parameters

HandleAsync(RawRequestContext, CancellationToken) method

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

Handles the raw request with full context.

Parameters

Returns

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

SchemaIndexEndpoint class

public sealed class SchemaIndexEndpoint : IStellaEndpoint<SchemaIndexResponse>

Endpoint that returns an index of all available schemas.

SchemaIndexEndpoint(ISchemaRegistry) constructor

public SchemaIndexEndpoint(ISchemaRegistry schemaRegistry)

Initializes a new instance of the SchemaIndexEndpointclass.

Parameters

HandleAsync(CancellationToken) method

public Task<SchemaIndexResponse> HandleAsync(CancellationToken cancellationToken)

Handles the request.

Parameters

Returns

The response.

SchemaIndexResponse record

public sealed record SchemaIndexResponse

Response model for the schema index endpoint.

SchemaIndexResponse() constructor

public SchemaIndexResponse()

Creates an instance of SchemaIndexResponse.

Endpoints property

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

List of endpoints with schema information.

StellaOps.Microservice.Streaming namespace

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.

StreamChunk record

public sealed record StreamChunk

Represents a chunk of streaming data.

StreamChunk() constructor

public StreamChunk()

Creates an instance of StreamChunk.

Data property

public byte[] Data { get; init; }

Gets the chunk data.

EndOfStream property

public bool EndOfStream { get; init; }

Gets a value indicating whether this is the final chunk.

SequenceNumber property

public int SequenceNumber { get; init; }

Gets the sequence number.

StreamingRequestBodyStream class

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.

StreamingRequestBodyStream(ChannelReader<StreamChunk>, CancellationToken) constructor

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

Initializes a new instance of the StreamingRequestBodyStreamclass.

Parameters

CanRead property

public override bool CanRead { get; }

See Stream.CanRead.

CanSeek property

public override bool CanSeek { get; }

See Stream.CanSeek.

CanWrite property

public override bool CanWrite { get; }

See Stream.CanWrite.

Length property

public override long Length { get; }

See Stream.Length.

Position property

public override long Position { get; set; }

See Stream.Position.

Flush() method

public override void Flush()

See Stream.Flush().

Read(byte[], int, int) method

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

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

ReadAsync(Memory<byte>, CancellationToken) method

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

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

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

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

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

Seek(long, SeekOrigin) method

public override long Seek(long offset, SeekOrigin origin)

See Stream.Seek(long, SeekOrigin).

SetLength(long) method

public override void SetLength(long value)

See Stream.SetLength(long).

Write(byte[], int, int) method

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

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

StreamingResponseBodyStream class

public sealed class StreamingResponseBodyStream : Stream

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

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

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

Initializes a new instance of the StreamingResponseBodyStreamclass.

Parameters

CanRead property

public override bool CanRead { get; }

See Stream.CanRead.

CanSeek property

public override bool CanSeek { get; }

See Stream.CanSeek.

CanWrite property

public override bool CanWrite { get; }

See Stream.CanWrite.

Length property

public override long Length { get; }

See Stream.Length.

Position property

public override long Position { get; set; }

See Stream.Position.

CompleteAsync(CancellationToken) method

public Task CompleteAsync(CancellationToken cancellationToken = default)

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

DisposeAsync() method

public override ValueTask DisposeAsync()

See Stream.DisposeAsync().

Flush() method

public override void Flush()

See Stream.Flush().

FlushAsync(CancellationToken) method

public override Task FlushAsync(CancellationToken cancellationToken)

See Stream.FlushAsync(CancellationToken).

Read(byte[], int, int) method

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

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

Seek(long, SeekOrigin) method

public override long Seek(long offset, SeekOrigin origin)

See Stream.Seek(long, SeekOrigin).

SetLength(long) method

public override void SetLength(long value)

See Stream.SetLength(long).

Write(byte[], int, int) method

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

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

WriteAsync(ReadOnlyMemory<byte>, CancellationToken) method

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

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

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

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

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

StellaOps.Microservice.Validation namespace

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.

EndpointSchemaDefinition record

public sealed record EndpointSchemaDefinition

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

Parameters

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

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 property

public string Method { get; init; }

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

Path property

public string Path { get; init; }

The endpoint path template.

RequestSchemaJson property

public string? RequestSchemaJson { get; init; }

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

ResponseSchemaJson property

public string? ResponseSchemaJson { get; init; }

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

ValidateRequest property

public bool ValidateRequest { get; init; }

Whether request validation is enabled.

ValidateResponse property

public bool ValidateResponse { get; init; }

Whether response validation is enabled.

IGeneratedSchemaProvider interface

public interface IGeneratedSchemaProvider

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

GetSchemaDefinitions() method

IReadOnlyList<EndpointSchemaDefinition> GetSchemaDefinitions()

Gets all endpoint schema definitions generated at compile time.

Returns

A list of all endpoint schema definitions.

IRequestSchemaValidator interface

public interface IRequestSchemaValidator

Validates JSON documents against JSON schemas.

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

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

Validates a JSON document against a schema.

Parameters

Returns

True if the document is valid, false otherwise.

ISchemaRegistry interface

public interface ISchemaRegistry

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

GetAllSchemas() method

IReadOnlyList<EndpointSchemaDefinition> GetAllSchemas()

Gets all registered schema definitions.

Returns

All endpoint schema definitions.

GetRequestSchema(string, string) method

JsonSchema? GetRequestSchema(string method, string path)

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

Parameters

Returns

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

GetResponseSchema(string, string) method

JsonSchema? GetResponseSchema(string method, string path)

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

Parameters

Returns

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

GetSchemaETag(string, string, SchemaDirection) method

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

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

Parameters

Returns

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

GetSchemaText(string, string, SchemaDirection) method

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

Gets the raw schema text for documentation/publication.

Parameters

Returns

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

HasSchema(string, string, SchemaDirection) method

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

Checks if an endpoint has a schema registered.

Parameters

Returns

True if a schema is registered.

RequestSchemaValidator class

public sealed class RequestSchemaValidator : IRequestSchemaValidator

Validates JSON documents against JSON schemas using JsonSchema.Net.

RequestSchemaValidator(ILogger<RequestSchemaValidator>) constructor

public RequestSchemaValidator(ILogger<RequestSchemaValidator> logger)

Creates a new request schema validator.

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

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

Validates a JSON document against a schema.

Parameters

Returns

True if the document is valid, false otherwise.

SchemaDirection enum

public enum SchemaDirection

Specifies the direction of schema validation.

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

SchemaRegistry class

public sealed class SchemaRegistry : ISchemaRegistry

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

SchemaRegistry(ILogger<SchemaRegistry>, IGeneratedSchemaProvider) constructor

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

Creates a new schema registry.

Parameters

GetAllSchemas() method

public IReadOnlyList<EndpointSchemaDefinition> GetAllSchemas()

Gets all registered schema definitions.

Returns

All endpoint schema definitions.

GetRequestSchema(string, string) method

public JsonSchema? GetRequestSchema(string method, string path)

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

Parameters

Returns

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

GetResponseSchema(string, string) method

public JsonSchema? GetResponseSchema(string method, string path)

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

Parameters

Returns

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

GetSchemaETag(string, string, SchemaDirection) method

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

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

Parameters

Returns

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

GetSchemaText(string, string, SchemaDirection) method

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

Gets the raw schema text for documentation/publication.

Parameters

Returns

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

HasSchema(string, string, SchemaDirection) method

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

Checks if an endpoint has a schema registered.

Parameters

Returns

True if a schema is registered.

SchemaValidationError record

public sealed record SchemaValidationError

Represents a single schema validation error.

Parameters

SchemaValidationError(string, string, string, string) constructor

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

Represents a single schema validation error.

Parameters

InstanceLocation property

public string InstanceLocation { get; init; }

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

Keyword property

public string Keyword { get; init; }

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

Message property

public string Message { get; init; }

Human-readable error message.

SchemaLocation property

public string SchemaLocation { get; init; }

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

SchemaValidationException class

public sealed class SchemaValidationException : Exception

Exception thrown when request or response body fails schema validation.

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

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

Creates a new schema validation exception.

Direction property

public SchemaDirection Direction { get; }

Gets whether this was request or response validation.

EndpointMethod property

public string EndpointMethod { get; }

Gets the HTTP method of the endpoint.

EndpointPath property

public string EndpointPath { get; }

Gets the endpoint path where validation failed.

Errors property

public IReadOnlyList<SchemaValidationError> Errors { get; }

Gets the list of validation errors.

ValidationProblemDetails class

public sealed class ValidationProblemDetails

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

ValidationProblemDetails() constructor

public ValidationProblemDetails()

Creates an instance of ValidationProblemDetails.

SchemaValidationType constant

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

Detail property

public string? Detail { get; init; }

A human-readable explanation specific to this occurrence.

Errors property

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

The list of validation errors.

Instance property

public string? Instance { get; init; }

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

Status property

public int Status { get; init; }

The HTTP status code (422).

Title property

public string Title { get; init; }

A short, human-readable summary of the problem.

TraceId property

public string? TraceId { get; init; }

The trace/correlation ID for distributed tracing.

Type property

public string Type { get; init; }

A URI reference identifying the problem type.

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

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

Creates a ValidationProblemDetails for schema validation failures.

Parameters

ToRawResponse() method

public RawResponse ToRawResponse()

Converts this problem details to a RawResponse.