Implement InMemory Transport Layer for StellaOps Router

- Added InMemoryTransportOptions class for configuration settings including timeouts and latency.
- Developed InMemoryTransportServer class to handle connections, frame processing, and event management.
- Created ServiceCollectionExtensions for easy registration of InMemory transport services.
- Established project structure and dependencies for InMemory transport library.
- Implemented comprehensive unit tests for endpoint discovery, connection management, request/response flow, and streaming capabilities.
- Ensured proper handling of cancellation, heartbeat, and hello frames within the transport layer.
This commit is contained in:
StellaOps Bot
2025-12-05 01:00:10 +02:00
parent 8768c27f30
commit 175b750e29
111 changed files with 25407 additions and 19242 deletions

View File

@@ -0,0 +1,75 @@
namespace StellaOps.Microservice;
/// <summary>
/// Default implementation of endpoint registry using path matchers.
/// </summary>
public sealed class EndpointRegistry : IEndpointRegistry
{
private readonly List<RegisteredEndpoint> _endpoints = [];
private readonly bool _caseInsensitive;
/// <summary>
/// Initializes a new instance of the <see cref="EndpointRegistry"/> class.
/// </summary>
/// <param name="caseInsensitive">Whether path matching should be case-insensitive.</param>
public EndpointRegistry(bool caseInsensitive = true)
{
_caseInsensitive = caseInsensitive;
}
/// <summary>
/// Registers an endpoint descriptor.
/// </summary>
/// <param name="endpoint">The endpoint descriptor to register.</param>
public void Register(EndpointDescriptor endpoint)
{
var matcher = new PathMatcher(endpoint.Path, _caseInsensitive);
_endpoints.Add(new RegisteredEndpoint(endpoint, matcher));
}
/// <summary>
/// Registers multiple endpoint descriptors.
/// </summary>
/// <param name="endpoints">The endpoint descriptors to register.</param>
public void RegisterAll(IEnumerable<EndpointDescriptor> endpoints)
{
foreach (var endpoint in endpoints)
{
Register(endpoint);
}
}
/// <inheritdoc />
public bool TryMatch(string method, string path, out EndpointMatch? match)
{
match = null;
foreach (var registered in _endpoints)
{
// Check method match (case-insensitive)
if (!string.Equals(registered.Endpoint.Method, method, StringComparison.OrdinalIgnoreCase))
continue;
// Check path match
if (registered.Matcher.TryMatch(path, out var parameters))
{
match = new EndpointMatch
{
Endpoint = registered.Endpoint,
PathParameters = parameters
};
return true;
}
}
return false;
}
/// <inheritdoc />
public IReadOnlyList<EndpointDescriptor> GetAllEndpoints()
{
return _endpoints.Select(e => e.Endpoint).ToList();
}
private sealed record RegisteredEndpoint(EndpointDescriptor Endpoint, PathMatcher Matcher);
}

View File

@@ -0,0 +1,102 @@
using System.Collections;
namespace StellaOps.Microservice;
/// <summary>
/// Default implementation of header collection.
/// </summary>
public sealed class HeaderCollection : IHeaderCollection
{
private readonly Dictionary<string, List<string>> _headers;
/// <summary>
/// Gets an empty header collection.
/// </summary>
public static readonly HeaderCollection Empty = new();
/// <summary>
/// Initializes a new instance of the <see cref="HeaderCollection"/> class.
/// </summary>
public HeaderCollection()
{
_headers = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Initializes a new instance from key-value pairs.
/// </summary>
public HeaderCollection(IEnumerable<KeyValuePair<string, string>> headers)
: this()
{
foreach (var kvp in headers)
{
Add(kvp.Key, kvp.Value);
}
}
/// <inheritdoc />
public string? this[string key]
{
get => _headers.TryGetValue(key, out var values) && values.Count > 0 ? values[0] : null;
}
/// <summary>
/// Adds a header value.
/// </summary>
/// <param name="key">The header key.</param>
/// <param name="value">The header value.</param>
public void Add(string key, string value)
{
if (!_headers.TryGetValue(key, out var values))
{
values = [];
_headers[key] = values;
}
values.Add(value);
}
/// <summary>
/// Sets a header, replacing any existing values.
/// </summary>
/// <param name="key">The header key.</param>
/// <param name="value">The header value.</param>
public void Set(string key, string value)
{
_headers[key] = [value];
}
/// <inheritdoc />
public IEnumerable<string> GetValues(string key)
{
return _headers.TryGetValue(key, out var values) ? values : [];
}
/// <inheritdoc />
public bool TryGetValue(string key, out string? value)
{
if (_headers.TryGetValue(key, out var values) && values.Count > 0)
{
value = values[0];
return true;
}
value = null;
return false;
}
/// <inheritdoc />
public bool ContainsKey(string key) => _headers.ContainsKey(key);
/// <inheritdoc />
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
foreach (var kvp in _headers)
{
foreach (var value in kvp.Value)
{
yield return new KeyValuePair<string, string>(kvp.Key, value);
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

View File

@@ -0,0 +1,15 @@
using StellaOps.Router.Common.Models;
namespace StellaOps.Microservice;
/// <summary>
/// Provides endpoint discovery functionality.
/// </summary>
public interface IEndpointDiscoveryProvider
{
/// <summary>
/// Discovers all endpoints in the application.
/// </summary>
/// <returns>The discovered endpoints.</returns>
IReadOnlyList<EndpointDescriptor> DiscoverEndpoints();
}

View File

@@ -0,0 +1,38 @@
namespace StellaOps.Microservice;
/// <summary>
/// Registry for looking up endpoint handlers by method and path.
/// </summary>
public interface IEndpointRegistry
{
/// <summary>
/// Tries to find a matching endpoint for the given method and path.
/// </summary>
/// <param name="method">The HTTP method.</param>
/// <param name="path">The request path.</param>
/// <param name="match">The matching endpoint information if found.</param>
/// <returns>True if a matching endpoint was found.</returns>
bool TryMatch(string method, string path, out EndpointMatch? match);
/// <summary>
/// Gets all registered endpoints.
/// </summary>
/// <returns>All registered endpoint descriptors.</returns>
IReadOnlyList<EndpointDescriptor> GetAllEndpoints();
}
/// <summary>
/// Represents a matched endpoint with extracted path parameters.
/// </summary>
public sealed class EndpointMatch
{
/// <summary>
/// Gets the matched endpoint descriptor.
/// </summary>
public required EndpointDescriptor Endpoint { get; init; }
/// <summary>
/// Gets the path parameters extracted from the URL.
/// </summary>
public required IReadOnlyDictionary<string, string> PathParameters { get; init; }
}

View File

@@ -0,0 +1,36 @@
namespace StellaOps.Microservice;
/// <summary>
/// Abstraction for HTTP-style header collection.
/// </summary>
public interface IHeaderCollection : IEnumerable<KeyValuePair<string, string>>
{
/// <summary>
/// Gets a header value by key.
/// </summary>
/// <param name="key">The header key (case-insensitive).</param>
/// <returns>The header value, or null if not found.</returns>
string? this[string key] { get; }
/// <summary>
/// Gets all values for a header key.
/// </summary>
/// <param name="key">The header key (case-insensitive).</param>
/// <returns>All values for the key.</returns>
IEnumerable<string> GetValues(string key);
/// <summary>
/// Tries to get a header value.
/// </summary>
/// <param name="key">The header key.</param>
/// <param name="value">The header value if found.</param>
/// <returns>True if the header was found.</returns>
bool TryGetValue(string key, out string? value);
/// <summary>
/// Checks if a header exists.
/// </summary>
/// <param name="key">The header key.</param>
/// <returns>True if the header exists.</returns>
bool ContainsKey(string key);
}

View File

@@ -0,0 +1,26 @@
using StellaOps.Router.Common.Models;
namespace StellaOps.Microservice;
/// <summary>
/// Manages connections to router gateways.
/// </summary>
public interface IRouterConnectionManager
{
/// <summary>
/// Gets the current connection states.
/// </summary>
IReadOnlyList<ConnectionState> Connections { get; }
/// <summary>
/// Starts the connection manager.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task StartAsync(CancellationToken cancellationToken);
/// <summary>
/// Stops the connection manager.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task StopAsync(CancellationToken cancellationToken);
}

View File

@@ -0,0 +1,52 @@
namespace StellaOps.Microservice;
/// <summary>
/// Marker interface for all Stella endpoints.
/// </summary>
public interface IStellaEndpoint
{
}
/// <summary>
/// Interface for a typed Stella endpoint with request and response.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
public interface IStellaEndpoint<TRequest, TResponse> : IStellaEndpoint
{
/// <summary>
/// Handles the request.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The response.</returns>
Task<TResponse> HandleAsync(TRequest request, CancellationToken cancellationToken);
}
/// <summary>
/// Interface for a typed Stella endpoint with response only (no request body).
/// </summary>
/// <typeparam name="TResponse">The response type.</typeparam>
public interface IStellaEndpoint<TResponse> : IStellaEndpoint
{
/// <summary>
/// Handles the request.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The response.</returns>
Task<TResponse> HandleAsync(CancellationToken cancellationToken);
}
/// <summary>
/// Interface for a raw Stella endpoint that handles requests with full context.
/// </summary>
public interface IRawStellaEndpoint : IStellaEndpoint
{
/// <summary>
/// Handles the raw request with full context.
/// </summary>
/// <param name="context">The request context including headers, path parameters, and body stream.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The raw response including status code, headers, and body stream.</returns>
Task<RawResponse> HandleAsync(RawRequestContext context, CancellationToken cancellationToken);
}

View File

@@ -0,0 +1,40 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace StellaOps.Microservice;
/// <summary>
/// Hosted service that manages the microservice lifecycle.
/// </summary>
public sealed class MicroserviceHostedService : IHostedService
{
private readonly IRouterConnectionManager _connectionManager;
private readonly ILogger<MicroserviceHostedService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MicroserviceHostedService"/> class.
/// </summary>
public MicroserviceHostedService(
IRouterConnectionManager connectionManager,
ILogger<MicroserviceHostedService> logger)
{
_connectionManager = connectionManager;
_logger = logger;
}
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting Stella microservice");
await _connectionManager.StartAsync(cancellationToken);
_logger.LogInformation("Stella microservice started");
}
/// <inheritdoc />
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping Stella microservice");
await _connectionManager.StopAsync(cancellationToken);
_logger.LogInformation("Stella microservice stopped");
}
}

View File

@@ -0,0 +1,85 @@
using System.Text.RegularExpressions;
namespace StellaOps.Microservice;
/// <summary>
/// Matches request paths against route templates.
/// </summary>
public sealed partial class PathMatcher
{
private readonly string _template;
private readonly Regex _regex;
private readonly string[] _parameterNames;
private readonly bool _caseInsensitive;
/// <summary>
/// Gets the route template.
/// </summary>
public string Template => _template;
/// <summary>
/// Initializes a new instance of the <see cref="PathMatcher"/> class.
/// </summary>
/// <param name="template">The route template (e.g., "/api/users/{id}").</param>
/// <param name="caseInsensitive">Whether matching should be case-insensitive.</param>
public PathMatcher(string template, bool caseInsensitive = true)
{
_template = template;
_caseInsensitive = caseInsensitive;
// Extract parameter names and build regex
var paramNames = new List<string>();
var pattern = "^" + ParameterRegex().Replace(template, match =>
{
paramNames.Add(match.Groups[1].Value);
return "([^/]+)";
}) + "/?$";
var options = caseInsensitive ? RegexOptions.IgnoreCase : RegexOptions.None;
_regex = new Regex(pattern, options | RegexOptions.Compiled);
_parameterNames = [.. paramNames];
}
/// <summary>
/// Tries to match a path against the template.
/// </summary>
/// <param name="path">The request path.</param>
/// <param name="parameters">The extracted path parameters if matched.</param>
/// <returns>True if the path matches.</returns>
public bool TryMatch(string path, out Dictionary<string, string> parameters)
{
parameters = [];
// Normalize path
path = path.TrimEnd('/');
if (!path.StartsWith('/'))
path = "/" + path;
var match = _regex.Match(path);
if (!match.Success)
return false;
for (int i = 0; i < _parameterNames.Length; i++)
{
parameters[_parameterNames[i]] = match.Groups[i + 1].Value;
}
return true;
}
/// <summary>
/// Checks if a path matches the template.
/// </summary>
/// <param name="path">The request path.</param>
/// <returns>True if the path matches.</returns>
public bool IsMatch(string path)
{
path = path.TrimEnd('/');
if (!path.StartsWith('/'))
path = "/" + path;
return _regex.IsMatch(path);
}
[GeneratedRegex(@"\{([^}:]+)(?::[^}]+)?\}")]
private static partial Regex ParameterRegex();
}

View File

@@ -0,0 +1,43 @@
namespace StellaOps.Microservice;
/// <summary>
/// Context for a raw request.
/// </summary>
public sealed class RawRequestContext
{
/// <summary>
/// Gets the HTTP method.
/// </summary>
public string Method { get; init; } = string.Empty;
/// <summary>
/// Gets the request path.
/// </summary>
public string Path { get; init; } = string.Empty;
/// <summary>
/// Gets the path parameters extracted from route templates.
/// </summary>
public IReadOnlyDictionary<string, string> PathParameters { get; init; }
= new Dictionary<string, string>();
/// <summary>
/// Gets the request headers.
/// </summary>
public IHeaderCollection Headers { get; init; } = HeaderCollection.Empty;
/// <summary>
/// Gets the request body stream.
/// </summary>
public Stream Body { get; init; } = Stream.Null;
/// <summary>
/// Gets the cancellation token.
/// </summary>
public CancellationToken CancellationToken { get; init; }
/// <summary>
/// Gets the correlation ID for request tracking.
/// </summary>
public string? CorrelationId { get; init; }
}

View File

@@ -0,0 +1,77 @@
using System.Text;
namespace StellaOps.Microservice;
/// <summary>
/// Represents a raw response from an endpoint.
/// </summary>
public sealed class RawResponse
{
/// <summary>
/// Gets or sets the HTTP status code.
/// </summary>
public int StatusCode { get; init; } = 200;
/// <summary>
/// Gets or sets the response headers.
/// </summary>
public IHeaderCollection Headers { get; init; } = HeaderCollection.Empty;
/// <summary>
/// Gets or sets the response body stream.
/// </summary>
public Stream Body { get; init; } = Stream.Null;
/// <summary>
/// Creates a 200 OK response with a body.
/// </summary>
public static RawResponse Ok(Stream body) => new() { StatusCode = 200, Body = body };
/// <summary>
/// Creates a 200 OK response with a byte array body.
/// </summary>
public static RawResponse Ok(byte[] body) => new() { StatusCode = 200, Body = new MemoryStream(body) };
/// <summary>
/// Creates a 200 OK response with a string body.
/// </summary>
public static RawResponse Ok(string body) => Ok(Encoding.UTF8.GetBytes(body));
/// <summary>
/// Creates a 204 No Content response.
/// </summary>
public static RawResponse NoContent() => new() { StatusCode = 204 };
/// <summary>
/// Creates a 400 Bad Request response.
/// </summary>
public static RawResponse BadRequest(string? message = null) =>
Error(400, message ?? "Bad Request");
/// <summary>
/// Creates a 404 Not Found response.
/// </summary>
public static RawResponse NotFound(string? message = null) =>
Error(404, message ?? "Not Found");
/// <summary>
/// Creates a 500 Internal Server Error response.
/// </summary>
public static RawResponse InternalError(string? message = null) =>
Error(500, message ?? "Internal Server Error");
/// <summary>
/// Creates an error response with a message body.
/// </summary>
public static RawResponse Error(int statusCode, string message)
{
var headers = new HeaderCollection();
headers.Set("Content-Type", "text/plain; charset=utf-8");
return new RawResponse
{
StatusCode = statusCode,
Headers = headers,
Body = new MemoryStream(Encoding.UTF8.GetBytes(message))
};
}
}

View File

@@ -0,0 +1,71 @@
using System.Reflection;
using StellaOps.Router.Common.Models;
namespace StellaOps.Microservice;
/// <summary>
/// Discovers endpoints using runtime reflection.
/// </summary>
public sealed class ReflectionEndpointDiscoveryProvider : IEndpointDiscoveryProvider
{
private readonly StellaMicroserviceOptions _options;
private readonly IEnumerable<Assembly> _assemblies;
/// <summary>
/// Initializes a new instance of the <see cref="ReflectionEndpointDiscoveryProvider"/> class.
/// </summary>
/// <param name="options">The microservice options.</param>
/// <param name="assemblies">The assemblies to scan for endpoints.</param>
public ReflectionEndpointDiscoveryProvider(StellaMicroserviceOptions options, IEnumerable<Assembly>? assemblies = null)
{
_options = options;
_assemblies = assemblies ?? AppDomain.CurrentDomain.GetAssemblies();
}
/// <inheritdoc />
public IReadOnlyList<EndpointDescriptor> DiscoverEndpoints()
{
var endpoints = new List<EndpointDescriptor>();
foreach (var assembly in _assemblies)
{
try
{
foreach (var type in assembly.GetTypes())
{
var attribute = type.GetCustomAttribute<StellaEndpointAttribute>();
if (attribute is null) continue;
if (!typeof(IStellaEndpoint).IsAssignableFrom(type))
{
throw new InvalidOperationException(
$"Type {type.FullName} has [StellaEndpoint] but does not implement IStellaEndpoint.");
}
var claims = attribute.RequiredClaims
.Select(c => new ClaimRequirement { Type = c })
.ToList();
var descriptor = new EndpointDescriptor
{
ServiceName = _options.ServiceName,
Version = _options.Version,
Method = attribute.Method,
Path = attribute.Path,
DefaultTimeout = TimeSpan.FromSeconds(attribute.TimeoutSeconds),
SupportsStreaming = attribute.SupportsStreaming,
RequiringClaims = claims
};
endpoints.Add(descriptor);
}
}
catch (ReflectionTypeLoadException)
{
// Skip assemblies that cannot be loaded
}
}
return endpoints;
}
}

View File

@@ -0,0 +1,219 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Router.Common.Abstractions;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Common.Models;
namespace StellaOps.Microservice;
/// <summary>
/// Manages connections to router gateways.
/// </summary>
public sealed class RouterConnectionManager : IRouterConnectionManager, IDisposable
{
private readonly StellaMicroserviceOptions _options;
private readonly IEndpointDiscoveryProvider _endpointDiscovery;
private readonly ITransportClient _transportClient;
private readonly ILogger<RouterConnectionManager> _logger;
private readonly ConcurrentDictionary<string, ConnectionState> _connections = new();
private readonly CancellationTokenSource _cts = new();
private IReadOnlyList<EndpointDescriptor>? _endpoints;
private Task? _heartbeatTask;
private bool _disposed;
/// <inheritdoc />
public IReadOnlyList<ConnectionState> Connections => [.. _connections.Values];
/// <summary>
/// Initializes a new instance of the <see cref="RouterConnectionManager"/> class.
/// </summary>
public RouterConnectionManager(
IOptions<StellaMicroserviceOptions> options,
IEndpointDiscoveryProvider endpointDiscovery,
ITransportClient transportClient,
ILogger<RouterConnectionManager> logger)
{
_options = options.Value;
_endpointDiscovery = endpointDiscovery;
_transportClient = transportClient;
_logger = logger;
}
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
_options.Validate();
_logger.LogInformation(
"Starting router connection manager for {ServiceName}/{Version}",
_options.ServiceName,
_options.Version);
// Discover endpoints
_endpoints = _endpointDiscovery.DiscoverEndpoints();
_logger.LogInformation("Discovered {EndpointCount} endpoints", _endpoints.Count);
// Connect to each router
foreach (var router in _options.Routers)
{
await ConnectToRouterAsync(router, cancellationToken);
}
// Start heartbeat task
_heartbeatTask = Task.Run(() => HeartbeatLoopAsync(_cts.Token), CancellationToken.None);
}
/// <inheritdoc />
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping router connection manager");
await _cts.CancelAsync();
if (_heartbeatTask is not null)
{
try
{
await _heartbeatTask.WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
// Expected
}
}
_connections.Clear();
}
private async Task ConnectToRouterAsync(RouterEndpointConfig router, CancellationToken cancellationToken)
{
var connectionId = $"{router.Host}:{router.Port}";
var backoff = _options.ReconnectBackoffInitial;
while (!cancellationToken.IsCancellationRequested)
{
try
{
_logger.LogInformation(
"Connecting to router at {Host}:{Port} via {Transport}",
router.Host,
router.Port,
router.TransportType);
// Create connection state
var instance = new InstanceDescriptor
{
InstanceId = _options.InstanceId,
ServiceName = _options.ServiceName,
Version = _options.Version,
Region = _options.Region
};
var state = new ConnectionState
{
ConnectionId = connectionId,
Instance = instance,
Status = InstanceHealthStatus.Healthy,
LastHeartbeatUtc = DateTime.UtcNow,
TransportType = router.TransportType
};
// Register endpoints
foreach (var endpoint in _endpoints ?? [])
{
state.Endpoints[(endpoint.Method, endpoint.Path)] = endpoint;
}
_connections[connectionId] = state;
// For InMemory transport, connectivity is handled via the transport client
// Real transports will establish actual network connections here
_logger.LogInformation(
"Connected to router at {Host}:{Port}, registered {EndpointCount} endpoints",
router.Host,
router.Port,
_endpoints?.Count ?? 0);
// Reset backoff on successful connection
backoff = _options.ReconnectBackoffInitial;
return;
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"Failed to connect to router at {Host}:{Port}, retrying in {Backoff}",
router.Host,
router.Port,
backoff);
await Task.Delay(backoff, cancellationToken);
// Exponential backoff
backoff = TimeSpan.FromTicks(Math.Min(
backoff.Ticks * 2,
_options.ReconnectBackoffMax.Ticks));
}
}
}
private async Task HeartbeatLoopAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await Task.Delay(_options.HeartbeatInterval, cancellationToken);
foreach (var connection in _connections.Values)
{
try
{
// Build heartbeat payload
var heartbeat = new HeartbeatPayload
{
InstanceId = _options.InstanceId,
Status = connection.Status,
TimestampUtc = DateTime.UtcNow
};
// Update last heartbeat time
connection.LastHeartbeatUtc = DateTime.UtcNow;
_logger.LogDebug(
"Sent heartbeat for connection {ConnectionId}",
connection.ConnectionId);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"Failed to send heartbeat for connection {ConnectionId}",
connection.ConnectionId);
}
}
}
catch (OperationCanceledException)
{
// Expected on shutdown
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error in heartbeat loop");
}
}
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_cts.Cancel();
_cts.Dispose();
}
}

View File

@@ -1,4 +1,4 @@
using StellaOps.Router.Common;
using StellaOps.Router.Common.Enums;
namespace StellaOps.Microservice;

View File

@@ -1,4 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
namespace StellaOps.Microservice;
@@ -20,9 +22,53 @@ public static class ServiceCollectionExtensions
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configure);
// Stub implementation - will be filled in later sprints
// Configure options
services.Configure(configure);
// Register endpoint discovery
services.TryAddSingleton<IEndpointDiscoveryProvider>(sp =>
{
var options = new StellaMicroserviceOptions { ServiceName = "", Version = "1.0.0", Region = "" };
configure(options);
return new ReflectionEndpointDiscoveryProvider(options);
});
// Register connection manager
services.TryAddSingleton<IRouterConnectionManager, RouterConnectionManager>();
// Register hosted service
services.AddHostedService<MicroserviceHostedService>();
return services;
}
/// <summary>
/// Adds Stella microservice services with a custom endpoint discovery provider.
/// </summary>
/// <typeparam name="TDiscovery">The endpoint discovery provider type.</typeparam>
/// <param name="services">The service collection.</param>
/// <param name="configure">Action to configure the microservice options.</param>
/// <returns>The service collection for chaining.</returns>
public static IServiceCollection AddStellaMicroservice<TDiscovery>(
this IServiceCollection services,
Action<StellaMicroserviceOptions> configure)
where TDiscovery : class, IEndpointDiscoveryProvider
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configure);
// Configure options
services.Configure(configure);
// Register custom endpoint discovery
services.TryAddSingleton<IEndpointDiscoveryProvider, TDiscovery>();
// Register connection manager
services.TryAddSingleton<IRouterConnectionManager, RouterConnectionManager>();
// Register hosted service
services.AddHostedService<MicroserviceHostedService>();
return services;
}
}

View File

@@ -0,0 +1,46 @@
namespace StellaOps.Microservice;
/// <summary>
/// Marks a class as a Stella endpoint handler.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class StellaEndpointAttribute : Attribute
{
/// <summary>
/// Gets the HTTP method for this endpoint.
/// </summary>
public string Method { get; }
/// <summary>
/// Gets the path for this endpoint.
/// </summary>
public string Path { get; }
/// <summary>
/// Gets or sets whether this endpoint supports streaming.
/// Default: false.
/// </summary>
public bool SupportsStreaming { get; set; }
/// <summary>
/// Gets or sets the default timeout in seconds.
/// Default: 30 seconds.
/// </summary>
public int TimeoutSeconds { get; set; } = 30;
/// <summary>
/// Gets or sets the required claim types for this endpoint.
/// </summary>
public string[] RequiredClaims { get; set; } = [];
/// <summary>
/// Initializes a new instance of the <see cref="StellaEndpointAttribute"/> class.
/// </summary>
/// <param name="method">The HTTP method.</param>
/// <param name="path">The endpoint path.</param>
public StellaEndpointAttribute(string method, string path)
{
Method = method?.ToUpperInvariant() ?? throw new ArgumentNullException(nameof(method));
Path = path ?? throw new ArgumentNullException(nameof(path));
}
}

View File

@@ -1,11 +1,11 @@
using StellaOps.Router.Common;
using System.Text.RegularExpressions;
namespace StellaOps.Microservice;
/// <summary>
/// Options for configuring a Stella microservice.
/// </summary>
public sealed class StellaMicroserviceOptions
public sealed partial class StellaMicroserviceOptions
{
/// <summary>
/// Gets or sets the service name.
@@ -14,6 +14,7 @@ public sealed class StellaMicroserviceOptions
/// <summary>
/// Gets or sets the semantic version.
/// Must be valid semver (e.g., "1.0.0", "2.1.0-beta.1").
/// </summary>
public required string Version { get; set; }
@@ -24,6 +25,7 @@ public sealed class StellaMicroserviceOptions
/// <summary>
/// Gets or sets the unique instance identifier.
/// Auto-generated if not provided.
/// </summary>
public string InstanceId { get; set; } = Guid.NewGuid().ToString("N");
@@ -36,5 +38,55 @@ public sealed class StellaMicroserviceOptions
/// <summary>
/// Gets or sets the optional path to a YAML config file for endpoint overrides.
/// </summary>
public string? EndpointConfigPath { get; set; }
public string? ConfigFilePath { get; set; }
/// <summary>
/// Gets or sets the heartbeat interval.
/// Default: 10 seconds.
/// </summary>
public TimeSpan HeartbeatInterval { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>
/// Gets or sets the maximum reconnect backoff.
/// Default: 1 minute.
/// </summary>
public TimeSpan ReconnectBackoffMax { get; set; } = TimeSpan.FromMinutes(1);
/// <summary>
/// Gets or sets the initial reconnect delay.
/// Default: 1 second.
/// </summary>
public TimeSpan ReconnectBackoffInitial { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>
/// Validates the options and throws if invalid.
/// </summary>
public void Validate()
{
if (string.IsNullOrWhiteSpace(ServiceName))
throw new InvalidOperationException("ServiceName is required.");
if (string.IsNullOrWhiteSpace(Version))
throw new InvalidOperationException("Version is required.");
if (!SemverRegex().IsMatch(Version))
throw new InvalidOperationException($"Version '{Version}' is not valid semver.");
if (string.IsNullOrWhiteSpace(Region))
throw new InvalidOperationException("Region is required.");
if (Routers.Count == 0)
throw new InvalidOperationException("At least one router endpoint is required.");
foreach (var router in Routers)
{
if (string.IsNullOrWhiteSpace(router.Host))
throw new InvalidOperationException("Router host is required.");
if (router.Port <= 0 || router.Port > 65535)
throw new InvalidOperationException($"Router port {router.Port} is invalid.");
}
}
[GeneratedRegex(@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$")]
private static partial Regex SemverRegex();
}

View File

@@ -8,6 +8,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.0-rc.2.25502.107" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,4 +1,6 @@
namespace StellaOps.Router.Common;
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Common.Abstractions;
/// <summary>
/// Provides global routing state derived from all live connections.
@@ -21,21 +23,9 @@ public interface IGlobalRoutingState
/// <param name="method">The HTTP method.</param>
/// <param name="path">The request path.</param>
/// <returns>The available connection states.</returns>
IEnumerable<ConnectionState> GetConnectionsForEndpoint(
IReadOnlyList<ConnectionState> GetConnectionsFor(
string serviceName,
string version,
string method,
string path);
/// <summary>
/// Registers a connection and its endpoints.
/// </summary>
/// <param name="connection">The connection state to register.</param>
void RegisterConnection(ConnectionState connection);
/// <summary>
/// Removes a connection from the routing state.
/// </summary>
/// <param name="connectionId">The connection ID to remove.</param>
void UnregisterConnection(string connectionId);
}

View File

@@ -0,0 +1,17 @@
namespace StellaOps.Router.Common.Abstractions;
/// <summary>
/// Provides region information for routing decisions.
/// </summary>
public interface IRegionProvider
{
/// <summary>
/// Gets the current gateway region.
/// </summary>
string Region { get; }
/// <summary>
/// Gets the neighbor regions in order of preference.
/// </summary>
IReadOnlyList<string> NeighborRegions { get; }
}

View File

@@ -0,0 +1,19 @@
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Common.Abstractions;
/// <summary>
/// Provides extensibility for routing decisions.
/// </summary>
public interface IRoutingPlugin
{
/// <summary>
/// Chooses an instance for the routing context.
/// </summary>
/// <param name="context">The routing context.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The routing decision, or null if this plugin cannot decide.</returns>
Task<RoutingDecision?> ChooseInstanceAsync(
RoutingContext context,
CancellationToken cancellationToken);
}

View File

@@ -0,0 +1,51 @@
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Common.Abstractions;
/// <summary>
/// Represents a transport client for sending requests to microservices.
/// </summary>
public interface ITransportClient
{
/// <summary>
/// Sends a request and waits for a response.
/// </summary>
/// <param name="connection">The connection to use.</param>
/// <param name="requestFrame">The request frame.</param>
/// <param name="timeout">The timeout for the request.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The response frame.</returns>
Task<Frame> SendRequestAsync(
ConnectionState connection,
Frame requestFrame,
TimeSpan timeout,
CancellationToken cancellationToken);
/// <summary>
/// Sends a cancellation request.
/// </summary>
/// <param name="connection">The connection to use.</param>
/// <param name="correlationId">The correlation ID of the request to cancel.</param>
/// <param name="reason">Optional reason for cancellation.</param>
Task SendCancelAsync(
ConnectionState connection,
Guid correlationId,
string? reason = null);
/// <summary>
/// Sends a streaming request and processes the streaming response.
/// </summary>
/// <param name="connection">The connection to use.</param>
/// <param name="requestHeader">The request header frame.</param>
/// <param name="requestBody">The request body stream.</param>
/// <param name="readResponseBody">Callback to read the response body stream.</param>
/// <param name="limits">Payload limits to enforce.</param>
/// <param name="cancellationToken">Cancellation token.</param>
Task SendStreamingAsync(
ConnectionState connection,
Frame requestHeader,
Stream requestBody,
Func<Stream, Task> readResponseBody,
PayloadLimits limits,
CancellationToken cancellationToken);
}

View File

@@ -0,0 +1,19 @@
namespace StellaOps.Router.Common.Abstractions;
/// <summary>
/// Represents a transport server that accepts connections from microservices.
/// </summary>
public interface ITransportServer
{
/// <summary>
/// Starts listening for incoming connections.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task StartAsync(CancellationToken cancellationToken);
/// <summary>
/// Stops accepting new connections.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task StopAsync(CancellationToken cancellationToken);
}

View File

@@ -1,4 +1,4 @@
namespace StellaOps.Router.Common;
namespace StellaOps.Router.Common.Enums;
/// <summary>
/// Defines the frame types used in the router protocol.

View File

@@ -1,4 +1,4 @@
namespace StellaOps.Router.Common;
namespace StellaOps.Router.Common.Enums;
/// <summary>
/// Defines the health status of a microservice instance.

View File

@@ -1,7 +1,8 @@
namespace StellaOps.Router.Common;
namespace StellaOps.Router.Common.Enums;
/// <summary>
/// Defines the transport types supported for microservice-to-router communication.
/// Note: HTTP is explicitly excluded per specification.
/// </summary>
public enum TransportType
{
@@ -21,9 +22,9 @@ public enum TransportType
Tcp,
/// <summary>
/// TLS/mTLS transport with certificate-based authentication.
/// Certificate-based TCP (TLS/mTLS) transport with certificate-based authentication.
/// </summary>
Tls,
Certificate,
/// <summary>
/// RabbitMQ transport for queue-based communication.

View File

@@ -1,24 +0,0 @@
namespace StellaOps.Router.Common;
/// <summary>
/// Provides extensibility for routing decisions.
/// </summary>
public interface IRoutingPlugin
{
/// <summary>
/// Gets the priority of this plugin. Lower values run first.
/// </summary>
int Priority { get; }
/// <summary>
/// Filters or reorders candidate connections for routing.
/// </summary>
/// <param name="candidates">The candidate connections.</param>
/// <param name="endpoint">The target endpoint.</param>
/// <param name="gatewayRegion">The gateway's region.</param>
/// <returns>The filtered/reordered connections.</returns>
IEnumerable<ConnectionState> Filter(
IEnumerable<ConnectionState> candidates,
EndpointDescriptor endpoint,
string gatewayRegion);
}

View File

@@ -1,24 +0,0 @@
namespace StellaOps.Router.Common;
/// <summary>
/// Represents a transport client that connects to routers.
/// </summary>
public interface ITransportClient : IAsyncDisposable
{
/// <summary>
/// Gets the transport type for this client.
/// </summary>
TransportType TransportType { get; }
/// <summary>
/// Connects to a router endpoint.
/// </summary>
/// <param name="host">The router host.</param>
/// <param name="port">The router port.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The established connection.</returns>
Task<ITransportConnection> ConnectAsync(
string host,
int port,
CancellationToken cancellationToken = default);
}

View File

@@ -1,37 +0,0 @@
namespace StellaOps.Router.Common;
/// <summary>
/// Represents a bidirectional transport connection.
/// </summary>
public interface ITransportConnection : IAsyncDisposable
{
/// <summary>
/// Gets the unique identifier for this connection.
/// </summary>
string ConnectionId { get; }
/// <summary>
/// Gets a value indicating whether the connection is open.
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Sends a frame over the connection.
/// </summary>
/// <param name="frame">The frame to send.</param>
/// <param name="cancellationToken">Cancellation token.</param>
ValueTask SendAsync(Frame frame, CancellationToken cancellationToken = default);
/// <summary>
/// Receives the next frame from the connection.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The received frame, or null if connection closed.</returns>
ValueTask<Frame?> ReceiveAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Closes the connection gracefully.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task CloseAsync(CancellationToken cancellationToken = default);
}

View File

@@ -1,45 +0,0 @@
namespace StellaOps.Router.Common;
/// <summary>
/// Represents a transport server that accepts connections from microservices.
/// </summary>
public interface ITransportServer : IAsyncDisposable
{
/// <summary>
/// Gets the transport type for this server.
/// </summary>
TransportType TransportType { get; }
/// <summary>
/// Starts listening for incoming connections.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task StartAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Stops accepting new connections.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
Task StopAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Occurs when a new connection is established.
/// </summary>
event EventHandler<TransportConnectionEventArgs>? ConnectionEstablished;
/// <summary>
/// Occurs when a connection is closed.
/// </summary>
event EventHandler<TransportConnectionEventArgs>? ConnectionClosed;
}
/// <summary>
/// Event arguments for transport connection events.
/// </summary>
public sealed class TransportConnectionEventArgs : EventArgs
{
/// <summary>
/// Gets the connection that triggered the event.
/// </summary>
public required ITransportConnection Connection { get; init; }
}

View File

@@ -0,0 +1,12 @@
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Payload for the Cancel frame.
/// </summary>
public sealed record CancelPayload
{
/// <summary>
/// Gets the reason for cancellation.
/// </summary>
public string? Reason { get; init; }
}

View File

@@ -1,4 +1,4 @@
namespace StellaOps.Router.Common;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Represents a claim requirement for endpoint authorization.

View File

@@ -1,4 +1,6 @@
namespace StellaOps.Router.Common;
using StellaOps.Router.Common.Enums;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Represents the state of a connection between a microservice and the router.

View File

@@ -1,4 +1,4 @@
namespace StellaOps.Router.Common;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Describes an endpoint's identity and metadata.

View File

@@ -1,4 +1,6 @@
namespace StellaOps.Router.Common;
using StellaOps.Router.Common.Enums;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Represents a protocol frame in the router transport layer.

View File

@@ -0,0 +1,34 @@
using StellaOps.Router.Common.Enums;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Payload for the Heartbeat frame sent periodically by microservices.
/// </summary>
public sealed record HeartbeatPayload
{
/// <summary>
/// Gets the instance ID.
/// </summary>
public required string InstanceId { get; init; }
/// <summary>
/// Gets the health status.
/// </summary>
public required InstanceHealthStatus Status { get; init; }
/// <summary>
/// Gets the current in-flight request count.
/// </summary>
public int InFlightRequestCount { get; init; }
/// <summary>
/// Gets the error rate (0.0 to 1.0).
/// </summary>
public double ErrorRate { get; init; }
/// <summary>
/// Gets the timestamp when this heartbeat was created.
/// </summary>
public DateTime TimestampUtc { get; init; } = DateTime.UtcNow;
}

View File

@@ -0,0 +1,17 @@
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Payload for the Hello frame sent by microservices on connection.
/// </summary>
public sealed record HelloPayload
{
/// <summary>
/// Gets the instance descriptor.
/// </summary>
public required InstanceDescriptor Instance { get; init; }
/// <summary>
/// Gets the endpoints registered by this instance.
/// </summary>
public required IReadOnlyList<EndpointDescriptor> Endpoints { get; init; }
}

View File

@@ -1,4 +1,4 @@
namespace StellaOps.Router.Common;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Describes a microservice instance's identity.

View File

@@ -0,0 +1,30 @@
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Configuration for payload and memory limits.
/// </summary>
public sealed record PayloadLimits
{
/// <summary>
/// Default payload limits.
/// </summary>
public static readonly PayloadLimits Default = new();
/// <summary>
/// Gets the maximum request bytes per call.
/// Default: 10 MB.
/// </summary>
public long MaxRequestBytesPerCall { get; init; } = 10 * 1024 * 1024;
/// <summary>
/// Gets the maximum request bytes per connection.
/// Default: 100 MB.
/// </summary>
public long MaxRequestBytesPerConnection { get; init; } = 100 * 1024 * 1024;
/// <summary>
/// Gets the maximum aggregate in-flight bytes across all requests.
/// Default: 1 GB.
/// </summary>
public long MaxAggregateInflightBytes { get; init; } = 1024 * 1024 * 1024;
}

View File

@@ -0,0 +1,48 @@
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Neutral routing context that does not depend on ASP.NET.
/// Gateway will adapt from HttpContext to this neutral model.
/// </summary>
public sealed record RoutingContext
{
/// <summary>
/// Gets the HTTP method (GET, POST, PUT, PATCH, DELETE).
/// </summary>
public required string Method { get; init; }
/// <summary>
/// Gets the request path.
/// </summary>
public required string Path { get; init; }
/// <summary>
/// Gets the request headers.
/// </summary>
public IReadOnlyDictionary<string, string> Headers { get; init; } = new Dictionary<string, string>();
/// <summary>
/// Gets the resolved endpoint descriptor.
/// </summary>
public EndpointDescriptor? Endpoint { get; init; }
/// <summary>
/// Gets the available connections for routing.
/// </summary>
public IReadOnlyList<ConnectionState> AvailableConnections { get; init; } = [];
/// <summary>
/// Gets the gateway's region for routing decisions.
/// </summary>
public required string GatewayRegion { get; init; }
/// <summary>
/// Gets the requested version, if specified.
/// </summary>
public string? RequestedVersion { get; init; }
/// <summary>
/// Gets the cancellation token for the request.
/// </summary>
public CancellationToken CancellationToken { get; init; }
}

View File

@@ -0,0 +1,29 @@
using StellaOps.Router.Common.Enums;
namespace StellaOps.Router.Common.Models;
/// <summary>
/// Represents the outcome of a routing decision.
/// </summary>
public sealed record RoutingDecision
{
/// <summary>
/// Gets the selected endpoint.
/// </summary>
public required EndpointDescriptor Endpoint { get; init; }
/// <summary>
/// Gets the selected connection.
/// </summary>
public required ConnectionState Connection { get; init; }
/// <summary>
/// Gets the transport type to use.
/// </summary>
public required TransportType TransportType { get; init; }
/// <summary>
/// Gets the effective timeout for the request.
/// </summary>
public required TimeSpan EffectiveTimeout { get; init; }
}

View File

@@ -1,25 +0,0 @@
namespace StellaOps.Router.Config;
/// <summary>
/// Configuration for payload and memory limits.
/// </summary>
public sealed class PayloadLimits
{
/// <summary>
/// Gets or sets the maximum request bytes per call.
/// Default: 10 MB.
/// </summary>
public long MaxRequestBytesPerCall { get; set; } = 10 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum request bytes per connection.
/// Default: 100 MB.
/// </summary>
public long MaxRequestBytesPerConnection { get; set; } = 100 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum aggregate in-flight bytes across all requests.
/// Default: 1 GB.
/// </summary>
public long MaxAggregateInflightBytes { get; set; } = 1024 * 1024 * 1024;
}

View File

@@ -1,3 +1,5 @@
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Config;
/// <summary>

View File

@@ -1,4 +1,5 @@
using StellaOps.Router.Common;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Config;

View File

@@ -0,0 +1,93 @@
using System.Threading.Channels;
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Transport.InMemory;
/// <summary>
/// Represents a bidirectional in-memory channel for frame passing between gateway and microservice.
/// </summary>
public sealed class InMemoryChannel : IDisposable
{
private bool _disposed;
/// <summary>
/// Gets the connection ID.
/// </summary>
public string ConnectionId { get; }
/// <summary>
/// Gets the channel for frames from gateway to microservice.
/// Gateway writes, SDK reads.
/// </summary>
public Channel<Frame> ToMicroservice { get; }
/// <summary>
/// Gets the channel for frames from microservice to gateway.
/// SDK writes, Gateway reads.
/// </summary>
public Channel<Frame> ToGateway { get; }
/// <summary>
/// Gets or sets the instance descriptor for this connection.
/// Set when HELLO is processed.
/// </summary>
public InstanceDescriptor? Instance { get; set; }
/// <summary>
/// Gets the cancellation token source for this connection's lifetime.
/// </summary>
public CancellationTokenSource LifetimeToken { get; }
/// <summary>
/// Gets or sets the connection state.
/// </summary>
public ConnectionState? State { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="InMemoryChannel"/> class.
/// </summary>
/// <param name="connectionId">The connection ID.</param>
/// <param name="bufferSize">The channel buffer size. Zero for unbounded.</param>
public InMemoryChannel(string connectionId, int bufferSize = 0)
{
ConnectionId = connectionId;
LifetimeToken = new CancellationTokenSource();
if (bufferSize > 0)
{
var options = new BoundedChannelOptions(bufferSize)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
};
ToMicroservice = Channel.CreateBounded<Frame>(options);
ToGateway = Channel.CreateBounded<Frame>(options);
}
else
{
var options = new UnboundedChannelOptions
{
SingleReader = false,
SingleWriter = false
};
ToMicroservice = Channel.CreateUnbounded<Frame>(options);
ToGateway = Channel.CreateUnbounded<Frame>(options);
}
}
/// <summary>
/// Disposes the channel and cancels all pending operations.
/// </summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
LifetimeToken.Cancel();
LifetimeToken.Dispose();
ToMicroservice.Writer.TryComplete();
ToGateway.Writer.TryComplete();
}
}

View File

@@ -0,0 +1,124 @@
using System.Collections.Concurrent;
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Transport.InMemory;
/// <summary>
/// Thread-safe registry for in-memory connections.
/// </summary>
public sealed class InMemoryConnectionRegistry : IDisposable
{
private readonly ConcurrentDictionary<string, InMemoryChannel> _channels = new();
private bool _disposed;
/// <summary>
/// Gets all connection IDs.
/// </summary>
public IEnumerable<string> ConnectionIds => _channels.Keys;
/// <summary>
/// Gets the count of active connections.
/// </summary>
public int Count => _channels.Count;
/// <summary>
/// Creates a new channel with the given connection ID.
/// </summary>
/// <param name="connectionId">The connection ID.</param>
/// <param name="bufferSize">The channel buffer size.</param>
/// <returns>The created channel.</returns>
public InMemoryChannel CreateChannel(string connectionId, int bufferSize = 0)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var channel = new InMemoryChannel(connectionId, bufferSize);
if (!_channels.TryAdd(connectionId, channel))
{
channel.Dispose();
throw new InvalidOperationException($"Connection {connectionId} already exists.");
}
return channel;
}
/// <summary>
/// Gets a channel by connection ID.
/// </summary>
/// <param name="connectionId">The connection ID.</param>
/// <returns>The channel, or null if not found.</returns>
public InMemoryChannel? GetChannel(string connectionId)
{
_channels.TryGetValue(connectionId, out var channel);
return channel;
}
/// <summary>
/// Gets a channel by connection ID, throwing if not found.
/// </summary>
/// <param name="connectionId">The connection ID.</param>
/// <returns>The channel.</returns>
public InMemoryChannel GetRequiredChannel(string connectionId)
{
return GetChannel(connectionId)
?? throw new InvalidOperationException($"Connection {connectionId} not found.");
}
/// <summary>
/// Removes and disposes a channel by connection ID.
/// </summary>
/// <param name="connectionId">The connection ID.</param>
/// <returns>True if the channel was found and removed.</returns>
public bool RemoveChannel(string connectionId)
{
if (_channels.TryRemove(connectionId, out var channel))
{
channel.Dispose();
return true;
}
return false;
}
/// <summary>
/// Gets all active connection states.
/// </summary>
public IReadOnlyList<ConnectionState> GetAllConnections()
{
return _channels.Values
.Where(c => c.State is not null)
.Select(c => c.State!)
.ToList();
}
/// <summary>
/// Gets connections for a specific service and endpoint.
/// </summary>
/// <param name="serviceName">The service name.</param>
/// <param name="version">The version.</param>
/// <param name="method">The HTTP method.</param>
/// <param name="path">The path.</param>
public IReadOnlyList<ConnectionState> GetConnectionsFor(
string serviceName, string version, string method, string path)
{
return _channels.Values
.Where(c => c.State is not null
&& c.Instance?.ServiceName == serviceName
&& c.Instance?.Version == version
&& c.State.Endpoints.ContainsKey((method, path)))
.Select(c => c.State!)
.ToList();
}
/// <summary>
/// Disposes all channels.
/// </summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
foreach (var channel in _channels.Values)
{
channel.Dispose();
}
_channels.Clear();
}
}

View File

@@ -0,0 +1,425 @@
using System.Buffers;
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Router.Common.Abstractions;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Transport.InMemory;
/// <summary>
/// In-memory transport client implementation for testing and development.
/// Used by the Microservice SDK to send frames to the Gateway.
/// </summary>
public sealed class InMemoryTransportClient : ITransportClient, IDisposable
{
private readonly InMemoryConnectionRegistry _registry;
private readonly InMemoryTransportOptions _options;
private readonly ILogger<InMemoryTransportClient> _logger;
private readonly ConcurrentDictionary<string, TaskCompletionSource<Frame>> _pendingRequests = new();
private readonly CancellationTokenSource _clientCts = new();
private bool _disposed;
private string? _connectionId;
private Task? _receiveTask;
/// <summary>
/// Event raised when a REQUEST frame is received from the gateway.
/// </summary>
public event Func<Frame, CancellationToken, Task<Frame>>? OnRequestReceived;
/// <summary>
/// Event raised when a CANCEL frame is received from the gateway.
/// </summary>
public event Func<Guid, string?, Task>? OnCancelReceived;
/// <summary>
/// Initializes a new instance of the <see cref="InMemoryTransportClient"/> class.
/// </summary>
public InMemoryTransportClient(
InMemoryConnectionRegistry registry,
IOptions<InMemoryTransportOptions> options,
ILogger<InMemoryTransportClient> logger)
{
_registry = registry;
_options = options.Value;
_logger = logger;
}
/// <summary>
/// Connects to the in-memory transport and sends a HELLO frame.
/// </summary>
/// <param name="instance">The instance descriptor.</param>
/// <param name="endpoints">The endpoints to register.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public async Task ConnectAsync(
InstanceDescriptor instance,
IReadOnlyList<EndpointDescriptor> endpoints,
CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
_connectionId = Guid.NewGuid().ToString("N");
var channel = _registry.CreateChannel(_connectionId, _options.ChannelBufferSize);
channel.Instance = instance;
// Create initial ConnectionState
var state = new ConnectionState
{
ConnectionId = _connectionId,
Instance = instance,
Status = InstanceHealthStatus.Healthy,
LastHeartbeatUtc = DateTime.UtcNow,
TransportType = TransportType.InMemory
};
// Register endpoints
foreach (var endpoint in endpoints)
{
state.Endpoints[(endpoint.Method, endpoint.Path)] = endpoint;
}
channel.State = state;
// Send HELLO frame
var helloFrame = new Frame
{
Type = FrameType.Hello,
CorrelationId = Guid.NewGuid().ToString("N"),
Payload = ReadOnlyMemory<byte>.Empty
};
await channel.ToGateway.Writer.WriteAsync(helloFrame, cancellationToken);
_logger.LogInformation(
"Connected as {ServiceName}/{Version} instance {InstanceId} with {EndpointCount} endpoints",
instance.ServiceName,
instance.Version,
instance.InstanceId,
endpoints.Count);
// Start receiving frames from gateway
_receiveTask = Task.Run(() => ReceiveLoopAsync(_clientCts.Token), CancellationToken.None);
}
private async Task ReceiveLoopAsync(CancellationToken cancellationToken)
{
if (_connectionId is null) return;
var channel = _registry.GetChannel(_connectionId);
if (channel is null) return;
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, channel.LifetimeToken.Token);
try
{
await foreach (var frame in channel.ToMicroservice.Reader.ReadAllAsync(linkedCts.Token))
{
if (_options.SimulatedLatency > TimeSpan.Zero)
{
await Task.Delay(_options.SimulatedLatency, linkedCts.Token);
}
await ProcessFrameFromGatewayAsync(channel, frame, linkedCts.Token);
}
}
catch (OperationCanceledException)
{
// Expected on disconnect
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in receive loop");
}
}
private async Task ProcessFrameFromGatewayAsync(
InMemoryChannel channel, Frame frame, CancellationToken cancellationToken)
{
switch (frame.Type)
{
case FrameType.Request:
case FrameType.RequestStreamData:
await HandleRequestFrameAsync(channel, frame, cancellationToken);
break;
case FrameType.Cancel:
HandleCancelFrame(frame);
break;
case FrameType.Response:
case FrameType.ResponseStreamData:
// Response to our request (from gateway back)
if (frame.CorrelationId is not null &&
_pendingRequests.TryRemove(frame.CorrelationId, out var tcs))
{
tcs.TrySetResult(frame);
}
break;
default:
_logger.LogWarning("Unexpected frame type {FrameType} from gateway", frame.Type);
break;
}
}
private async Task HandleRequestFrameAsync(
InMemoryChannel channel, Frame frame, CancellationToken cancellationToken)
{
if (OnRequestReceived is null)
{
_logger.LogWarning("No request handler registered, discarding request {CorrelationId}",
frame.CorrelationId);
return;
}
try
{
var response = await OnRequestReceived(frame, cancellationToken);
// Ensure response has same correlation ID
var responseFrame = response with { CorrelationId = frame.CorrelationId };
await channel.ToGateway.Writer.WriteAsync(responseFrame, cancellationToken);
}
catch (OperationCanceledException)
{
_logger.LogDebug("Request {CorrelationId} was cancelled", frame.CorrelationId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling request {CorrelationId}", frame.CorrelationId);
// Send error response
var errorFrame = new Frame
{
Type = FrameType.Response,
CorrelationId = frame.CorrelationId,
Payload = ReadOnlyMemory<byte>.Empty
};
await channel.ToGateway.Writer.WriteAsync(errorFrame, cancellationToken);
}
}
private void HandleCancelFrame(Frame frame)
{
if (frame.CorrelationId is null) return;
_logger.LogDebug("Received CANCEL for correlation {CorrelationId}", frame.CorrelationId);
// Complete any pending request with cancellation
if (_pendingRequests.TryRemove(frame.CorrelationId, out var tcs))
{
tcs.TrySetCanceled();
}
// Notify handler
if (OnCancelReceived is not null && Guid.TryParse(frame.CorrelationId, out var correlationGuid))
{
_ = OnCancelReceived(correlationGuid, null);
}
}
/// <inheritdoc />
public async Task<Frame> SendRequestAsync(
ConnectionState connection,
Frame requestFrame,
TimeSpan timeout,
CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var channel = _registry.GetRequiredChannel(connection.ConnectionId);
var correlationId = requestFrame.CorrelationId ?? Guid.NewGuid().ToString("N");
var framedRequest = requestFrame with { CorrelationId = correlationId };
var tcs = new TaskCompletionSource<Frame>(TaskCreationOptions.RunContinuationsAsynchronously);
_pendingRequests[correlationId] = tcs;
try
{
if (_options.SimulatedLatency > TimeSpan.Zero)
{
await Task.Delay(_options.SimulatedLatency, cancellationToken);
}
await channel.ToMicroservice.Writer.WriteAsync(framedRequest, cancellationToken);
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCts.CancelAfter(timeout);
return await tcs.Task.WaitAsync(timeoutCts.Token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException($"Request {correlationId} timed out after {timeout}");
}
finally
{
_pendingRequests.TryRemove(correlationId, out _);
}
}
/// <inheritdoc />
public async Task SendCancelAsync(
ConnectionState connection,
Guid correlationId,
string? reason = null)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var channel = _registry.GetRequiredChannel(connection.ConnectionId);
var cancelFrame = new Frame
{
Type = FrameType.Cancel,
CorrelationId = correlationId.ToString("N"),
Payload = ReadOnlyMemory<byte>.Empty
};
if (_options.SimulatedLatency > TimeSpan.Zero)
{
await Task.Delay(_options.SimulatedLatency);
}
await channel.ToMicroservice.Writer.WriteAsync(cancelFrame);
_logger.LogDebug("Sent CANCEL for correlation {CorrelationId}", correlationId);
}
/// <inheritdoc />
public async Task SendStreamingAsync(
ConnectionState connection,
Frame requestHeader,
Stream requestBody,
Func<Stream, Task> readResponseBody,
PayloadLimits limits,
CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var channel = _registry.GetRequiredChannel(connection.ConnectionId);
var correlationId = requestHeader.CorrelationId ?? Guid.NewGuid().ToString("N");
// Send header frame
var headerFrame = requestHeader with
{
Type = FrameType.Request,
CorrelationId = correlationId
};
await channel.ToMicroservice.Writer.WriteAsync(headerFrame, cancellationToken);
// Stream request body in chunks
var buffer = ArrayPool<byte>.Shared.Rent(8192);
try
{
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await requestBody.ReadAsync(buffer, cancellationToken)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead > limits.MaxRequestBytesPerCall)
{
throw new InvalidOperationException(
$"Request body exceeds limit of {limits.MaxRequestBytesPerCall} bytes");
}
var dataFrame = new Frame
{
Type = FrameType.RequestStreamData,
CorrelationId = correlationId,
Payload = new ReadOnlyMemory<byte>(buffer, 0, bytesRead)
};
await channel.ToMicroservice.Writer.WriteAsync(dataFrame, cancellationToken);
if (_options.SimulatedLatency > TimeSpan.Zero)
{
await Task.Delay(_options.SimulatedLatency, cancellationToken);
}
}
// Signal end of request stream with empty data frame
var endFrame = new Frame
{
Type = FrameType.RequestStreamData,
CorrelationId = correlationId,
Payload = ReadOnlyMemory<byte>.Empty
};
await channel.ToMicroservice.Writer.WriteAsync(endFrame, cancellationToken);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
// Read streaming response
using var responseStream = new MemoryStream();
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_pendingRequests[correlationId] = new TaskCompletionSource<Frame>();
// TODO: Implement proper streaming response handling
// For now, we accumulate the response in memory
await readResponseBody(responseStream);
}
/// <summary>
/// Sends a heartbeat frame.
/// </summary>
public async Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)
{
if (_connectionId is null) return;
var channel = _registry.GetChannel(_connectionId);
if (channel is null) return;
var frame = new Frame
{
Type = FrameType.Heartbeat,
CorrelationId = null,
Payload = ReadOnlyMemory<byte>.Empty
};
await channel.ToGateway.Writer.WriteAsync(frame, cancellationToken);
}
/// <summary>
/// Disconnects from the transport.
/// </summary>
public async Task DisconnectAsync()
{
if (_connectionId is null) return;
await _clientCts.CancelAsync();
if (_receiveTask is not null)
{
await _receiveTask;
}
_registry.RemoveChannel(_connectionId);
_connectionId = null;
_logger.LogInformation("Disconnected from in-memory transport");
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_clientCts.Cancel();
foreach (var tcs in _pendingRequests.Values)
{
tcs.TrySetCanceled();
}
_pendingRequests.Clear();
if (_connectionId is not null)
{
_registry.RemoveChannel(_connectionId);
}
_clientCts.Dispose();
}
}

View File

@@ -0,0 +1,37 @@
namespace StellaOps.Router.Transport.InMemory;
/// <summary>
/// Configuration options for the InMemory transport.
/// </summary>
public sealed class InMemoryTransportOptions
{
/// <summary>
/// Gets or sets the default timeout for requests.
/// Default: 30 seconds.
/// </summary>
public TimeSpan DefaultTimeout { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Gets or sets the simulated latency for frame delivery.
/// Default: Zero (instant delivery).
/// </summary>
public TimeSpan SimulatedLatency { get; set; } = TimeSpan.Zero;
/// <summary>
/// Gets or sets the channel buffer size.
/// Default: Unbounded (0 means unbounded).
/// </summary>
public int ChannelBufferSize { get; set; }
/// <summary>
/// Gets or sets the heartbeat interval.
/// Default: 10 seconds.
/// </summary>
public TimeSpan HeartbeatInterval { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>
/// Gets or sets the heartbeat timeout (time since last heartbeat before connection is considered unhealthy).
/// Default: 30 seconds.
/// </summary>
public TimeSpan HeartbeatTimeout { get; set; } = TimeSpan.FromSeconds(30);
}

View File

@@ -0,0 +1,264 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Router.Common.Abstractions;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Common.Models;
namespace StellaOps.Router.Transport.InMemory;
/// <summary>
/// In-memory transport server implementation for testing and development.
/// Used by the Gateway to receive frames from microservices.
/// </summary>
public sealed class InMemoryTransportServer : ITransportServer, IDisposable
{
private readonly InMemoryConnectionRegistry _registry;
private readonly InMemoryTransportOptions _options;
private readonly ILogger<InMemoryTransportServer> _logger;
private readonly ConcurrentDictionary<string, Task> _connectionTasks = new();
private readonly CancellationTokenSource _serverCts = new();
private bool _running;
private bool _disposed;
/// <summary>
/// Event raised when a HELLO frame is received.
/// </summary>
public event Func<ConnectionState, HelloPayload, Task>? OnHelloReceived;
/// <summary>
/// Event raised when a HEARTBEAT frame is received.
/// </summary>
public event Func<ConnectionState, HeartbeatPayload, Task>? OnHeartbeatReceived;
/// <summary>
/// Event raised when a RESPONSE frame is received.
/// </summary>
public event Func<ConnectionState, Frame, Task>? OnResponseReceived;
/// <summary>
/// Event raised when a connection is closed.
/// </summary>
public event Func<string, Task>? OnConnectionClosed;
/// <summary>
/// Initializes a new instance of the <see cref="InMemoryTransportServer"/> class.
/// </summary>
public InMemoryTransportServer(
InMemoryConnectionRegistry registry,
IOptions<InMemoryTransportOptions> options,
ILogger<InMemoryTransportServer> logger)
{
_registry = registry;
_options = options.Value;
_logger = logger;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_running)
{
_logger.LogWarning("InMemory transport server is already running");
return Task.CompletedTask;
}
_running = true;
_logger.LogInformation("InMemory transport server started");
return Task.CompletedTask;
}
/// <inheritdoc />
public async Task StopAsync(CancellationToken cancellationToken)
{
if (!_running) return;
_logger.LogInformation("InMemory transport server stopping");
_running = false;
await _serverCts.CancelAsync();
// Wait for all connection tasks to complete
var tasks = _connectionTasks.Values.ToArray();
if (tasks.Length > 0)
{
await Task.WhenAll(tasks).WaitAsync(cancellationToken);
}
_logger.LogInformation("InMemory transport server stopped");
}
/// <summary>
/// Starts listening to a specific connection's ToGateway channel.
/// Called when a new connection is registered.
/// </summary>
public void StartListeningToConnection(string connectionId)
{
if (!_running) return;
var channel = _registry.GetChannel(connectionId);
if (channel is null) return;
var task = Task.Run(async () =>
{
try
{
await ProcessConnectionFramesAsync(channel, _serverCts.Token);
}
catch (OperationCanceledException)
{
// Expected on shutdown
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing frames for connection {ConnectionId}", connectionId);
}
finally
{
_connectionTasks.TryRemove(connectionId, out _);
if (OnConnectionClosed is not null)
{
await OnConnectionClosed(connectionId);
}
}
});
_connectionTasks[connectionId] = task;
}
private async Task ProcessConnectionFramesAsync(InMemoryChannel channel, CancellationToken cancellationToken)
{
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, channel.LifetimeToken.Token);
await foreach (var frame in channel.ToGateway.Reader.ReadAllAsync(linkedCts.Token))
{
if (_options.SimulatedLatency > TimeSpan.Zero)
{
await Task.Delay(_options.SimulatedLatency, linkedCts.Token);
}
await ProcessFrameAsync(channel, frame, linkedCts.Token);
}
}
private async Task ProcessFrameAsync(InMemoryChannel channel, Frame frame, CancellationToken cancellationToken)
{
switch (frame.Type)
{
case FrameType.Hello:
await ProcessHelloFrameAsync(channel, frame, cancellationToken);
break;
case FrameType.Heartbeat:
await ProcessHeartbeatFrameAsync(channel, frame, cancellationToken);
break;
case FrameType.Response:
case FrameType.ResponseStreamData:
if (channel.State is not null && OnResponseReceived is not null)
{
await OnResponseReceived(channel.State, frame);
}
break;
case FrameType.Cancel:
_logger.LogDebug("Received CANCEL from microservice for correlation {CorrelationId}",
frame.CorrelationId);
break;
default:
_logger.LogWarning("Unexpected frame type {FrameType} from connection {ConnectionId}",
frame.Type, channel.ConnectionId);
break;
}
}
private async Task ProcessHelloFrameAsync(InMemoryChannel channel, Frame frame, CancellationToken cancellationToken)
{
// In a real implementation, we'd deserialize the payload
// For now, the HelloPayload should be passed out-of-band via the channel
if (channel.Instance is null)
{
_logger.LogWarning("HELLO received but Instance not set for connection {ConnectionId}",
channel.ConnectionId);
return;
}
// Create ConnectionState
var state = new ConnectionState
{
ConnectionId = channel.ConnectionId,
Instance = channel.Instance,
Status = InstanceHealthStatus.Healthy,
LastHeartbeatUtc = DateTime.UtcNow,
TransportType = TransportType.InMemory
};
channel.State = state;
_logger.LogInformation(
"HELLO received from {ServiceName}/{Version} instance {InstanceId}",
channel.Instance.ServiceName,
channel.Instance.Version,
channel.Instance.InstanceId);
// Fire event with dummy HelloPayload (real impl would deserialize from frame)
if (OnHelloReceived is not null)
{
var payload = new HelloPayload
{
Instance = channel.Instance,
Endpoints = []
};
await OnHelloReceived(state, payload);
}
}
private async Task ProcessHeartbeatFrameAsync(InMemoryChannel channel, Frame frame, CancellationToken cancellationToken)
{
if (channel.State is null) return;
channel.State.LastHeartbeatUtc = DateTime.UtcNow;
_logger.LogDebug("Heartbeat received from {ConnectionId}", channel.ConnectionId);
if (OnHeartbeatReceived is not null)
{
var payload = new HeartbeatPayload
{
InstanceId = channel.Instance?.InstanceId ?? channel.ConnectionId,
Status = channel.State.Status,
TimestampUtc = DateTime.UtcNow
};
await OnHeartbeatReceived(channel.State, payload);
}
}
/// <summary>
/// Sends a frame to a microservice via the ToMicroservice channel.
/// </summary>
public async ValueTask SendToMicroserviceAsync(
string connectionId, Frame frame, CancellationToken cancellationToken)
{
var channel = _registry.GetRequiredChannel(connectionId);
if (_options.SimulatedLatency > TimeSpan.Zero)
{
await Task.Delay(_options.SimulatedLatency, cancellationToken);
}
await channel.ToMicroservice.Writer.WriteAsync(frame, cancellationToken);
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_serverCts.Cancel();
_serverCts.Dispose();
}
}

View File

@@ -0,0 +1,87 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using StellaOps.Router.Common.Abstractions;
namespace StellaOps.Router.Transport.InMemory;
/// <summary>
/// Extension methods for registering InMemory transport services.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the InMemory transport for testing and development.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configure">Optional configuration action.</param>
/// <returns>The service collection for chaining.</returns>
public static IServiceCollection AddInMemoryTransport(
this IServiceCollection services,
Action<InMemoryTransportOptions>? configure = null)
{
services.AddOptions<InMemoryTransportOptions>();
if (configure is not null)
{
services.Configure(configure);
}
// Singleton registry shared between server and client
services.TryAddSingleton<InMemoryConnectionRegistry>();
// Transport implementations
services.TryAddSingleton<InMemoryTransportServer>();
services.TryAddSingleton<InMemoryTransportClient>();
// Register interfaces
services.TryAddSingleton<ITransportServer>(sp => sp.GetRequiredService<InMemoryTransportServer>());
services.TryAddSingleton<ITransportClient>(sp => sp.GetRequiredService<InMemoryTransportClient>());
return services;
}
/// <summary>
/// Adds the InMemory transport server only (for Gateway).
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configure">Optional configuration action.</param>
/// <returns>The service collection for chaining.</returns>
public static IServiceCollection AddInMemoryTransportServer(
this IServiceCollection services,
Action<InMemoryTransportOptions>? configure = null)
{
services.AddOptions<InMemoryTransportOptions>();
if (configure is not null)
{
services.Configure(configure);
}
services.TryAddSingleton<InMemoryConnectionRegistry>();
services.TryAddSingleton<InMemoryTransportServer>();
services.TryAddSingleton<ITransportServer>(sp => sp.GetRequiredService<InMemoryTransportServer>());
return services;
}
/// <summary>
/// Adds the InMemory transport client only (for Microservice SDK).
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configure">Optional configuration action.</param>
/// <returns>The service collection for chaining.</returns>
public static IServiceCollection AddInMemoryTransportClient(
this IServiceCollection services,
Action<InMemoryTransportOptions>? configure = null)
{
services.AddOptions<InMemoryTransportOptions>();
if (configure is not null)
{
services.Configure(configure);
}
services.TryAddSingleton<InMemoryConnectionRegistry>();
services.TryAddSingleton<InMemoryTransportClient>();
services.TryAddSingleton<ITransportClient>(sp => sp.GetRequiredService<InMemoryTransportClient>());
return services;
}
}

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>StellaOps.Router.Transport.InMemory</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\StellaOps.Router.Common\StellaOps.Router.Common.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.0-rc.2.25502.107" />
</ItemGroup>
</Project>