Files
git.stella-ops.org/docs/router/README.md
StellaOps Bot e6c47c8f50 save progress
2025-12-28 23:49:56 +02:00

295 lines
10 KiB
Markdown

# StellaOps Router
**Transport-agnostic microservice communication framework with plugin-based transport loading**
The StellaOps Router is a high-performance, production-grade framework for building distributed microservice architectures. It provides a unified API for service-to-service communication across multiple transport protocols, with automatic service discovery, OpenAPI aggregation, compile-time endpoint validation, and **runtime transport plugin loading**.
## Key Features
- **Multi-Transport Support**: InMemory, TCP, TLS/mTLS, RabbitMQ, UDP, Valkey/Redis, PostgreSQL
- **Plugin-Based Transports**: Transports loaded at runtime via `IRouterTransportPlugin` interface
- **Compile-Time Code Generation**: Source generators create endpoint descriptors and schema providers at build time
- **Gateway Pattern**: HTTP ingress with automatic routing to backend microservices
- **OpenAPI Aggregation**: Unified Swagger documentation from all connected services
- **Streaming Support**: First-class support for large payloads and server-sent events
- **JSON Schema Validation**: Optional request/response validation with `[ValidateSchema]`
- **Zero-Configuration Discovery**: Services auto-register with the gateway on startup
## Architecture
```
┌─────────────────────────────────────────────────────────────────────┐
│ HTTP Clients │
│ (Browser, CLI, Mobile) │
└─────────────────────────────┬───────────────────────────────────────┘
│ HTTPS
┌─────────────────────────────────────────────────────────────────────┐
│ Router Gateway │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │
│ │ OpenAPI Agg │ │ Auth/AuthZ │ │ Route Resolution │ │
│ └──────────────┘ └──────────────┘ └──────────────────────────┘ │
└─────────────────────────────┬───────────────────────────────────────┘
│ Binary Transport (TCP/TLS/RabbitMQ)
┌──────────────────┼──────────────────┐
▼ ▼ ▼
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐
│ Billing │ │ Inventory │ │ Notification │
│ Microservice │ │ Microservice │ │ Microservice │
│ │ │ │ │ │
│ [StellaEndpoint] │ │ [StellaEndpoint] │ │ [StellaEndpoint] │
└───────────────────┘ └───────────────────┘ └───────────────────┘
```
## Quick Start
### 1. Create a Microservice
```csharp
using StellaOps.Microservice;
using StellaOps.Router.Transport.InMemory;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddStellaMicroservice(options =>
{
options.ServiceName = "my-service";
options.Version = "1.0.0";
options.ConfigFilePath = "microservice.yaml";
});
builder.Services.AddInMemoryTransport();
builder.Services.AddScoped<MyEndpoint>();
var host = builder.Build();
await host.RunAsync();
```
### 2. Define Endpoints
```csharp
using StellaOps.Microservice;
// Typed endpoint with automatic JSON serialization
[StellaEndpoint("POST", "/orders", TimeoutSeconds = 30)]
public sealed class CreateOrderEndpoint : IStellaEndpoint<CreateOrderRequest, CreateOrderResponse>
{
public Task<CreateOrderResponse> HandleAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
return Task.FromResult(new CreateOrderResponse
{
OrderId = $"ORD-{Guid.NewGuid():N}"[..16]
});
}
}
// Raw endpoint for streaming
[StellaEndpoint("POST", "/files/{id}", SupportsStreaming = true)]
public sealed class UploadFileEndpoint : IRawStellaEndpoint
{
public async Task<RawResponse> HandleAsync(
RawRequestContext context,
CancellationToken cancellationToken)
{
var fileId = context.PathParameters["id"];
await using var stream = context.Body;
// Process stream...
var headers = new HeaderCollection();
headers.Set("Content-Type", "application/json");
return new RawResponse
{
StatusCode = 201,
Headers = headers,
Body = new MemoryStream("""{"status":"uploaded"}"""u8.ToArray())
};
}
}
```
### 3. Configure the Gateway
```csharp
using StellaOps.Router.Gateway;
using StellaOps.Router.Gateway.DependencyInjection;
using StellaOps.Router.Transport.InMemory;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRouterGateway(builder.Configuration);
builder.Services.AddInMemoryTransport();
builder.Services.AddAuthentication();
var app = builder.Build();
app.UseAuthentication();
app.UseClaimsAuthorization();
app.MapRouterOpenApi();
app.UseRouterGateway();
app.Run();
```
## Transport Plugins
Transport implementations are loaded at runtime via the plugin system. See [Transport Plugins](./transports/README.md) for full documentation.
| Transport | Plugin Assembly | Use Case | Performance |
|-----------|-----------------|----------|-------------|
| **InMemory** | `StellaOps.Router.Transport.InMemory.dll` | Development, testing | Sub-microsecond |
| **TCP** | `StellaOps.Router.Transport.Tcp.dll` | Internal services | < 1ms latency |
| **TLS** | `StellaOps.Router.Transport.Tls.dll` | Cross-datacenter, mTLS | < 2ms latency |
| **RabbitMQ** | `StellaOps.Router.Transport.RabbitMq.dll` | Async processing | Queue-based |
| **UDP** | `StellaOps.Router.Transport.Udp.dll` | Fire-and-forget | Best effort |
| **Valkey** | `StellaOps.Messaging.Transport.Valkey.dll` | Distributed, pub/sub | Memory-fast |
| **PostgreSQL** | `StellaOps.Messaging.Transport.Postgres.dll` | Transactional | Persistent |
### Loading Transport Plugins
```csharp
using StellaOps.Router.Common.Plugins;
// Load transport plugins from directory
var pluginLoader = new RouterTransportPluginLoader(logger);
pluginLoader.LoadFromDirectory("plugins/router/transports");
// Register the configured transport (reads Router:Transport:Type from config)
pluginLoader.RegisterConfiguredTransport(services, configuration);
```
### Configuring Transport
```yaml
# router.yaml
Router:
Transport:
Type: tls # Which transport plugin to use
Tls:
Port: 5101
CertificatePath: /certs/server.pfx
RequireClientCertificate: true
```
## Project Structure
```
src/Router/
├── StellaOps.Gateway.WebService/ # Gateway HTTP entrypoint
├── __Libraries/
│ ├── StellaOps.Router.Gateway/ # Gateway core logic
│ ├── StellaOps.Router.Common/ # Shared models and enums
│ ├── StellaOps.Router.Config/ # YAML configuration
│ ├── StellaOps.Router.AspNet/ # ASP.NET Core integration
│ ├── StellaOps.Microservice/ # Microservice SDK
│ ├── StellaOps.Microservice.SourceGen/ # Compile-time generator
│ ├── StellaOps.Messaging/ # Queue abstractions
│ └── StellaOps.Router.Transport.*/ # Transport implementations
├── __Tests/ # Unit and integration tests
└── examples/ # Working examples
├── Examples.OrderService/
├── Examples.NotificationService/
└── Examples.MultiTransport.Gateway/
```
## Configuration
### microservice.yaml
```yaml
service:
name: billing-service
version: 1.0.0
region: us-east-1
instanceId: billing-001
endpoints:
- path: /invoices
method: POST
timeoutSeconds: 30
- path: /invoices/{id}
method: GET
timeoutSeconds: 10
routers:
- host: gateway.internal
port: 5100
transportType: Tcp
priority: 1
- host: gateway-backup.internal
port: 5100
transportType: Tcp
priority: 2
heartbeat:
intervalSeconds: 30
reconnect:
initialDelayMs: 1000
maxDelayMs: 60000
```
### router.yaml (Gateway)
```yaml
gateway:
name: api-gateway
region: us-east-1
transports:
tcp:
port: 5100
maxConnections: 1000
tls:
port: 5101
certificatePath: /certs/server.pfx
requireClientCertificate: true
routing:
defaultTimeout: 30
maxRequestBodyBytes: 10485760
services:
billing:
routes:
- path: /invoices
methods: [GET, POST]
- path: /invoices/{id}
methods: [GET, PUT, DELETE]
inventory:
routes:
- path: /items
methods: [GET]
```
## Building
```bash
# Build the Router solution
dotnet build src/Router/StellaOps.Router.sln
# Run tests
dotnet test src/Router/StellaOps.Router.sln
# Build specific example
dotnet run --project src/Router/examples/Examples.OrderService
```
## Documentation
- [Architecture Overview](./ARCHITECTURE.md)
- [Getting Started Guide](./GETTING_STARTED.md)
- [Transport Configuration](./transports/)
- [Rate Limiting](./rate-limiting.md)
- [Examples](./examples/README.md)
## Related Modules
- **Authority**: OAuth/OIDC integration for gateway authentication
- **Policy**: Route-level authorization policies
- **Telemetry**: Distributed tracing across microservices
## License
AGPL-3.0-or-later