Add unit tests for Router configuration and transport layers
Some checks failed
Docs CI / lint-and-preview (push) Has been cancelled
Policy Lint & Smoke / policy-lint (push) Has been cancelled

- Implemented tests for RouterConfig, RoutingOptions, StaticInstanceConfig, and RouterConfigOptions to ensure default values are set correctly.
- Added tests for RouterConfigProvider to validate configurations and ensure defaults are returned when no file is specified.
- Created tests for ConfigValidationResult to check success and error scenarios.
- Developed tests for ServiceCollectionExtensions to verify service registration for RouterConfig.
- Introduced UdpTransportTests to validate serialization, connection, request-response, and error handling in UDP transport.
- Added scripts for signing authority gaps and hashing DevPortal SDK snippets.
This commit is contained in:
StellaOps Bot
2025-12-05 08:01:47 +02:00
parent 635c70e828
commit 6a299d231f
294 changed files with 28434 additions and 1329 deletions

View File

@@ -0,0 +1,37 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples.Gateway", "src\Examples.Gateway\Examples.Gateway.csproj", "{A1B2C3D4-E5F6-1234-5678-9ABCDEF01234}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples.Billing.Microservice", "src\Examples.Billing.Microservice\Examples.Billing.Microservice.csproj", "{B2C3D4E5-F6A1-2345-6789-ABCDEF012345}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples.Inventory.Microservice", "src\Examples.Inventory.Microservice\Examples.Inventory.Microservice.csproj", "{C3D4E5F6-A1B2-3456-789A-BCDEF0123456}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples.Integration.Tests", "tests\Examples.Integration.Tests\Examples.Integration.Tests.csproj", "{D4E5F6A1-B2C3-4567-89AB-CDEF01234567}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A1B2C3D4-E5F6-1234-5678-9ABCDEF01234}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A1B2C3D4-E5F6-1234-5678-9ABCDEF01234}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A1B2C3D4-E5F6-1234-5678-9ABCDEF01234}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A1B2C3D4-E5F6-1234-5678-9ABCDEF01234}.Release|Any CPU.Build.0 = Release|Any CPU
{B2C3D4E5-F6A1-2345-6789-ABCDEF012345}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2C3D4E5-F6A1-2345-6789-ABCDEF012345}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2C3D4E5-F6A1-2345-6789-ABCDEF012345}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2C3D4E5-F6A1-2345-6789-ABCDEF012345}.Release|Any CPU.Build.0 = Release|Any CPU
{C3D4E5F6-A1B2-3456-789A-BCDEF0123456}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3D4E5F6-A1B2-3456-789A-BCDEF0123456}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3D4E5F6-A1B2-3456-789A-BCDEF0123456}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3D4E5F6-A1B2-3456-789A-BCDEF0123456}.Release|Any CPU.Build.0 = Release|Any CPU
{D4E5F6A1-B2C3-4567-89AB-CDEF01234567}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4E5F6A1-B2C3-4567-89AB-CDEF01234567}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4E5F6A1-B2C3-4567-89AB-CDEF01234567}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4E5F6A1-B2C3-4567-89AB-CDEF01234567}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

297
examples/router/README.md Normal file
View File

@@ -0,0 +1,297 @@
# StellaOps Router Example
This example demonstrates the StellaOps Router, Gateway, and Microservice SDK working together.
## Overview
The example includes:
- **Examples.Gateway** - HTTP gateway that routes requests to microservices
- **Examples.Billing.Microservice** - Sample billing service with typed and streaming endpoints
- **Examples.Inventory.Microservice** - Sample inventory service demonstrating multi-service routing
- **Examples.Integration.Tests** - End-to-end integration tests
## Prerequisites
- .NET 10 SDK
- Docker and Docker Compose (for containerized deployment)
## Project Structure
```
examples/router/
├── Examples.Router.sln
├── docker-compose.yaml
├── README.md
├── src/
│ ├── Examples.Gateway/
│ │ ├── Program.cs
│ │ ├── router.yaml
│ │ └── appsettings.json
│ ├── Examples.Billing.Microservice/
│ │ ├── Program.cs
│ │ ├── microservice.yaml
│ │ └── Endpoints/
│ │ ├── CreateInvoiceEndpoint.cs
│ │ ├── GetInvoiceEndpoint.cs
│ │ └── UploadAttachmentEndpoint.cs
│ └── Examples.Inventory.Microservice/
│ ├── Program.cs
│ └── Endpoints/
│ ├── ListItemsEndpoint.cs
│ └── GetItemEndpoint.cs
└── tests/
└── Examples.Integration.Tests/
```
## Running Locally
### Build the Solution
```bash
cd examples/router
dotnet build Examples.Router.sln
```
### Run with Docker Compose
```bash
docker-compose up --build
```
This starts:
- Gateway on port 8080 (HTTP) and 5100 (TCP transport)
- Billing microservice
- Inventory microservice
- RabbitMQ (optional, for message-based transport)
### Run Without Docker
Start each service in separate terminals:
```bash
# Terminal 1: Gateway
cd src/Examples.Gateway
dotnet run
# Terminal 2: Billing Microservice
cd src/Examples.Billing.Microservice
dotnet run
# Terminal 3: Inventory Microservice
cd src/Examples.Inventory.Microservice
dotnet run
```
## Example API Calls
### Billing Service
Create an invoice:
```bash
curl -X POST http://localhost:8080/invoices \
-H "Content-Type: application/json" \
-d '{"customerId": "CUST-001", "amount": 99.99, "description": "Service fee"}'
```
Get an invoice:
```bash
curl http://localhost:8080/invoices/INV-12345
```
Upload an attachment (streaming):
```bash
curl -X POST http://localhost:8080/invoices/INV-12345/attachments \
-H "Content-Type: application/octet-stream" \
--data-binary @document.pdf
```
### Inventory Service
List items:
```bash
curl "http://localhost:8080/items?page=1&pageSize=20"
```
List items by category:
```bash
curl "http://localhost:8080/items?category=widgets"
```
Get a specific item:
```bash
curl http://localhost:8080/items/SKU-001
```
## Adding New Endpoints
### 1. Create the Endpoint Class
```csharp
using StellaOps.Microservice;
[StellaEndpoint("POST", "/orders", TimeoutSeconds = 30)]
public sealed class CreateOrderEndpoint : IStellaEndpoint<CreateOrderRequest, CreateOrderResponse>
{
public Task<CreateOrderResponse> HandleAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
// Implementation
return Task.FromResult(new CreateOrderResponse { OrderId = "ORD-123" });
}
}
```
### 2. Register in Program.cs
```csharp
builder.Services.AddScoped<CreateOrderEndpoint>();
```
### 3. Update router.yaml (if needed)
Add routing rules for the new endpoint path.
## Streaming Endpoints
For endpoints that handle large payloads (file uploads, etc.), implement `IRawStellaEndpoint`:
```csharp
[StellaEndpoint("POST", "/files/{id}", SupportsStreaming = true)]
public sealed class UploadFileEndpoint : IRawStellaEndpoint
{
public async Task<RawResponse> HandleAsync(
RawRequestContext context,
CancellationToken cancellationToken)
{
var id = context.PathParameters["id"];
// Stream body directly without buffering
await using var stream = context.Body;
// Process stream...
return RawResponse.Ok("{}");
}
}
```
## Cancellation Behavior
All endpoints receive a `CancellationToken` that is triggered when:
1. The client disconnects
2. The request timeout is exceeded
3. The gateway shuts down
Always respect the cancellation token in long-running operations:
```csharp
public async Task<Response> HandleAsync(Request request, CancellationToken ct)
{
// Check cancellation periodically
ct.ThrowIfCancellationRequested();
// Or pass to async operations
await SomeLongOperation(ct);
}
```
## Payload Limits
Default limits are configured in `router.yaml`:
```yaml
payloadLimits:
maxRequestBodySizeBytes: 10485760 # 10 MB
maxChunkSizeBytes: 65536 # 64 KB
```
For streaming endpoints, the body is not buffered so these limits apply per-chunk.
## Running Tests
```bash
cd tests/Examples.Integration.Tests
dotnet test
```
The integration tests verify:
- End-to-end request routing
- Multi-service registration
- Streaming uploads
- Request cancellation
- Payload limit enforcement
## Configuration
### Gateway (router.yaml)
```yaml
# Microservice routing rules
services:
billing:
routes:
- path: /invoices
methods: [GET, POST]
- path: /invoices/{id}
methods: [GET, PUT, DELETE]
- path: /invoices/{id}/attachments
methods: [POST]
inventory:
routes:
- path: /items
methods: [GET]
- path: /items/{sku}
methods: [GET]
```
### Microservice (microservice.yaml)
```yaml
service:
name: billing
version: 1.0.0
region: demo
endpoints:
- path: /invoices
method: POST
timeoutSeconds: 30
- path: /invoices/{id}
method: GET
timeoutSeconds: 10
routers:
- host: localhost
port: 5100
transportType: InMemory
```
## Troubleshooting
### Microservice not registering
Check that:
1. Gateway is running and healthy
2. Router host/port in microservice.yaml matches gateway
3. Network connectivity between services
### Request timeouts
Increase the timeout in the endpoint attribute:
```csharp
[StellaEndpoint("POST", "/long-operation", TimeoutSeconds = 120)]
```
### Streaming not working
Ensure the endpoint:
1. Is marked with `SupportsStreaming = true`
2. Implements `IRawStellaEndpoint`
3. Does not buffer the entire body before processing
## License
AGPL-3.0-or-later

View File

@@ -0,0 +1,75 @@
version: '3.8'
services:
gateway:
build:
context: .
dockerfile: src/Examples.Gateway/Dockerfile
ports:
- "8080:8080" # HTTP ingress
- "5100:5100" # TCP transport
- "5101:5101" # TLS transport
environment:
- ASPNETCORE_URLS=http://+:8080
- GatewayNode__Region=demo
- GatewayNode__NodeId=gw-01
- GatewayNode__ListenPort=5100
volumes:
- ./src/Examples.Gateway/router.yaml:/app/router.yaml:ro
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 10s
timeout: 5s
retries: 3
billing:
build:
context: .
dockerfile: src/Examples.Billing.Microservice/Dockerfile
environment:
- Stella__ServiceName=billing
- Stella__Region=demo
- Stella__Routers__0__Host=gateway
- Stella__Routers__0__Port=5100
- Stella__Routers__0__TransportType=InMemory
volumes:
- ./src/Examples.Billing.Microservice/microservice.yaml:/app/microservice.yaml:ro
depends_on:
gateway:
condition: service_healthy
inventory:
build:
context: .
dockerfile: src/Examples.Inventory.Microservice/Dockerfile
environment:
- Stella__ServiceName=inventory
- Stella__Region=demo
- Stella__Routers__0__Host=gateway
- Stella__Routers__0__Port=5100
- Stella__Routers__0__TransportType=InMemory
depends_on:
gateway:
condition: service_healthy
# Optional: RabbitMQ for message-based transport
rabbitmq:
image: rabbitmq:3-management-alpine
ports:
- "5672:5672" # AMQP
- "15672:15672" # Management UI
environment:
- RABBITMQ_DEFAULT_USER=stellaops
- RABBITMQ_DEFAULT_PASS=stellaops
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "check_running"]
interval: 10s
timeout: 5s
retries: 3
networks:
default:
name: stellaops-router-example
volumes:
rabbitmq-data:

View File

@@ -0,0 +1,70 @@
using Microsoft.Extensions.Logging;
using StellaOps.Microservice;
namespace Examples.Billing.Microservice.Endpoints;
/// <summary>
/// Request model for creating an invoice.
/// </summary>
public sealed record CreateInvoiceRequest
{
public required string CustomerId { get; init; }
public required decimal Amount { get; init; }
public string? Description { get; init; }
public List<LineItem> LineItems { get; init; } = [];
}
/// <summary>
/// Line item for an invoice.
/// </summary>
public sealed record LineItem
{
public required string Description { get; init; }
public required decimal Amount { get; init; }
public int Quantity { get; init; } = 1;
}
/// <summary>
/// Response model after creating an invoice.
/// </summary>
public sealed record CreateInvoiceResponse
{
public required string InvoiceId { get; init; }
public required DateTime CreatedAt { get; init; }
public required string Status { get; init; }
}
/// <summary>
/// Endpoint for creating a new invoice.
/// Demonstrates a typed endpoint with JSON request/response.
/// </summary>
[StellaEndpoint("POST", "/invoices", TimeoutSeconds = 30)]
public sealed class CreateInvoiceEndpoint : IStellaEndpoint<CreateInvoiceRequest, CreateInvoiceResponse>
{
private readonly ILogger<CreateInvoiceEndpoint> _logger;
public CreateInvoiceEndpoint(ILogger<CreateInvoiceEndpoint> logger)
{
_logger = logger;
}
public Task<CreateInvoiceResponse> HandleAsync(
CreateInvoiceRequest request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Creating invoice for customer {CustomerId} with amount {Amount}",
request.CustomerId,
request.Amount);
// Simulate invoice creation
var invoiceId = $"INV-{Guid.NewGuid():N}".ToUpperInvariant()[..16];
return Task.FromResult(new CreateInvoiceResponse
{
InvoiceId = invoiceId,
CreatedAt = DateTime.UtcNow,
Status = "draft"
});
}
}

View File

@@ -0,0 +1,58 @@
using Microsoft.Extensions.Logging;
using StellaOps.Microservice;
namespace Examples.Billing.Microservice.Endpoints;
/// <summary>
/// Request model for getting an invoice.
/// </summary>
public sealed record GetInvoiceRequest
{
public required string Id { get; init; }
}
/// <summary>
/// Response model for an invoice.
/// </summary>
public sealed record GetInvoiceResponse
{
public required string InvoiceId { get; init; }
public required string CustomerId { get; init; }
public required decimal Amount { get; init; }
public required string Status { get; init; }
public required DateTime CreatedAt { get; init; }
public DateTime? PaidAt { get; init; }
}
/// <summary>
/// Endpoint for retrieving an invoice by ID.
/// Demonstrates a GET endpoint with path parameters.
/// </summary>
[StellaEndpoint("GET", "/invoices/{id}", TimeoutSeconds = 10, RequiredClaims = ["invoices:read"])]
public sealed class GetInvoiceEndpoint : IStellaEndpoint<GetInvoiceRequest, GetInvoiceResponse>
{
private readonly ILogger<GetInvoiceEndpoint> _logger;
public GetInvoiceEndpoint(ILogger<GetInvoiceEndpoint> logger)
{
_logger = logger;
}
public Task<GetInvoiceResponse> HandleAsync(
GetInvoiceRequest request,
CancellationToken cancellationToken)
{
_logger.LogInformation("Fetching invoice {InvoiceId}", request.Id);
// Simulate invoice lookup
return Task.FromResult(new GetInvoiceResponse
{
InvoiceId = request.Id,
CustomerId = "CUST-001",
Amount = 199.99m,
Status = "paid",
CreatedAt = DateTime.UtcNow.AddDays(-7),
PaidAt = DateTime.UtcNow.AddDays(-1)
});
}
}

View File

@@ -0,0 +1,60 @@
using System.Text.Json;
using Microsoft.Extensions.Logging;
using StellaOps.Microservice;
namespace Examples.Billing.Microservice.Endpoints;
/// <summary>
/// Endpoint for uploading attachments to an invoice.
/// Demonstrates streaming upload using IRawStellaEndpoint.
/// </summary>
[StellaEndpoint("POST", "/invoices/{id}/attachments", SupportsStreaming = true, TimeoutSeconds = 300)]
public sealed class UploadAttachmentEndpoint : IRawStellaEndpoint
{
private readonly ILogger<UploadAttachmentEndpoint> _logger;
public UploadAttachmentEndpoint(ILogger<UploadAttachmentEndpoint> logger)
{
_logger = logger;
}
public async Task<RawResponse> HandleAsync(
RawRequestContext context,
CancellationToken cancellationToken)
{
var invoiceId = context.PathParameters.GetValueOrDefault("id") ?? "unknown";
var contentType = context.Headers["Content-Type"] ?? "application/octet-stream";
_logger.LogInformation(
"Uploading attachment for invoice {InvoiceId}, Content-Type: {ContentType}",
invoiceId,
contentType);
// Read the streamed body
long totalBytes = 0;
var buffer = new byte[8192];
int bytesRead;
while ((bytesRead = await context.Body.ReadAsync(buffer, cancellationToken)) > 0)
{
totalBytes += bytesRead;
// In a real implementation, you would write to storage here
}
_logger.LogInformation(
"Received {TotalBytes} bytes for invoice {InvoiceId}",
totalBytes,
invoiceId);
// Return success response
var response = new
{
invoiceId,
attachmentId = $"ATT-{Guid.NewGuid():N}"[..16].ToUpperInvariant(),
size = totalBytes,
uploadedAt = DateTime.UtcNow
};
return RawResponse.Ok(JsonSerializer.Serialize(response));
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.0-rc.2.25502.107" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Microservice\StellaOps.Microservice.csproj" />
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Router.Common\StellaOps.Router.Common.csproj" />
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Router.Transport.InMemory\StellaOps.Router.Transport.InMemory.csproj" />
<!-- Reference the source generator -->
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Microservice.SourceGen\StellaOps.Microservice.SourceGen.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<Content Include="microservice.yaml" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,40 @@
using Examples.Billing.Microservice.Endpoints;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StellaOps.Microservice;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Transport.InMemory;
var builder = Host.CreateApplicationBuilder(args);
// Configure the Stella microservice
builder.Services.AddStellaMicroservice(options =>
{
options.ServiceName = "billing";
options.Version = "1.0.0";
options.Region = "demo";
options.InstanceId = $"billing-{Environment.MachineName}";
options.ConfigFilePath = "microservice.yaml";
options.Routers =
[
new RouterEndpointConfig
{
Host = "localhost",
Port = 5100,
TransportType = TransportType.InMemory
}
];
});
// Register endpoint handlers
builder.Services.AddScoped<CreateInvoiceEndpoint>();
builder.Services.AddScoped<GetInvoiceEndpoint>();
builder.Services.AddScoped<UploadAttachmentEndpoint>();
// Add in-memory transport
builder.Services.AddInMemoryTransport();
var host = builder.Build();
Console.WriteLine("Billing microservice starting...");
await host.RunAsync();

View File

@@ -0,0 +1,21 @@
# Microservice YAML Configuration for Billing Service
# Overrides code-defined endpoint settings
endpoints:
# Override timeout for invoice creation
- method: POST
path: /invoices
timeout: 45s # Allow more time for complex invoice creation
# Override streaming settings for file upload
- method: POST
path: /invoices/{id}/attachments
timeout: 5m # Allow large file uploads
streaming: true
# Add claim requirements for getting invoices
- method: GET
path: /invoices/{id}
requiringClaims:
- type: "scope"
value: "invoices:read"

View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Gateway\StellaOps.Gateway.WebService\StellaOps.Gateway.WebService.csproj" />
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Router.Transport.InMemory\StellaOps.Router.Transport.InMemory.csproj" />
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Router.Config\StellaOps.Router.Config.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="router.yaml" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,53 @@
using StellaOps.Gateway.WebService;
using StellaOps.Gateway.WebService.Authorization;
using StellaOps.Gateway.WebService.Middleware;
using StellaOps.Router.Config;
using StellaOps.Router.Transport.InMemory;
var builder = WebApplication.CreateBuilder(args);
// Router configuration from YAML
builder.Services.AddRouterConfig(options =>
{
options.ConfigPath = "router.yaml";
options.EnableHotReload = true;
});
// Gateway routing services
builder.Services.AddGatewayRouting(builder.Configuration);
// In-memory transport for demo (can switch to TCP/TLS for production)
builder.Services.AddInMemoryTransport();
// Authority integration (no-op for demo)
builder.Services.AddNoOpAuthorityIntegration();
var app = builder.Build();
// Middleware pipeline
app.UseForwardedHeaders();
app.UseMiddleware<PayloadLimitsMiddleware>();
app.UseAuthentication();
app.UseMiddleware<EndpointResolutionMiddleware>();
app.UseClaimsAuthorization();
app.UseMiddleware<RoutingDecisionMiddleware>();
// Simple health endpoint
app.MapGet("/health", () => Results.Ok(new { status = "healthy" }));
// Catch-all for routed requests
app.MapFallback(async context =>
{
// The RoutingDecisionMiddleware would have dispatched the request
// If we reach here, no route was found
context.Response.StatusCode = 404;
await context.Response.WriteAsJsonAsync(new { error = "Not Found", message = "No matching endpoint" });
});
app.Run();
// Partial class for WebApplicationFactory integration testing
namespace Examples.Gateway
{
public partial class Program { }
}

View File

@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"GatewayNode": {
"Region": "demo",
"NodeId": "gw-demo-01"
}
}

View File

@@ -0,0 +1,50 @@
# Router Configuration for Example Gateway
# This file configures how the gateway routes requests to microservices
gateway:
nodeId: "gw-demo-01"
region: "demo"
listenPort: 8080
# Payload limits
payloadLimits:
maxRequestBodyBytes: 10485760 # 10 MB
maxStreamingChunkBytes: 65536 # 64 KB
# Health monitoring
healthMonitoring:
staleThreshold: "00:00:30"
checkInterval: "00:00:05"
# Transport configuration
transports:
# In-memory transport (for demo)
inMemory:
enabled: true
# TCP transport (production)
# tcp:
# enabled: true
# port: 5100
# backlog: 100
# TLS transport (production with encryption)
# tls:
# enabled: true
# port: 5101
# certificatePath: "certs/gateway.pfx"
# certificatePassword: "demo"
# Routing configuration
routing:
# Default routing algorithm
algorithm: "round-robin"
# Region affinity (prefer local microservices)
regionAffinity: true
affinityWeight: 0.8
# Logging
logging:
level: "Information"
requestLogging: true

View File

@@ -0,0 +1,64 @@
using Microsoft.Extensions.Logging;
using StellaOps.Microservice;
namespace Examples.Inventory.Microservice.Endpoints;
/// <summary>
/// Request model for getting a single inventory item.
/// </summary>
public sealed record GetItemRequest
{
public required string Sku { get; init; }
}
/// <summary>
/// Response model for a single inventory item with details.
/// </summary>
public sealed record GetItemResponse
{
public required string Sku { get; init; }
public required string Name { get; init; }
public required string Description { get; init; }
public required string Category { get; init; }
public required int QuantityOnHand { get; init; }
public required int ReorderPoint { get; init; }
public required decimal UnitPrice { get; init; }
public required string Location { get; init; }
public required DateTime LastUpdated { get; init; }
}
/// <summary>
/// Endpoint for getting a single inventory item by SKU.
/// Demonstrates path parameter extraction.
/// </summary>
[StellaEndpoint("GET", "/items/{sku}", TimeoutSeconds = 10)]
public sealed class GetItemEndpoint : IStellaEndpoint<GetItemRequest, GetItemResponse>
{
private readonly ILogger<GetItemEndpoint> _logger;
public GetItemEndpoint(ILogger<GetItemEndpoint> logger)
{
_logger = logger;
}
public Task<GetItemResponse> HandleAsync(
GetItemRequest request,
CancellationToken cancellationToken)
{
_logger.LogInformation("Fetching inventory item {Sku}", request.Sku);
// Simulate item lookup
return Task.FromResult(new GetItemResponse
{
Sku = request.Sku,
Name = "Widget A",
Description = "A high-quality widget for general purpose use",
Category = "widgets",
QuantityOnHand = 100,
ReorderPoint = 25,
UnitPrice = 9.99m,
Location = "Warehouse A, Aisle 3, Shelf 2",
LastUpdated = DateTime.UtcNow.AddHours(-2)
});
}
}

View File

@@ -0,0 +1,107 @@
using Microsoft.Extensions.Logging;
using StellaOps.Microservice;
namespace Examples.Inventory.Microservice.Endpoints;
/// <summary>
/// Request model for listing inventory items.
/// </summary>
public sealed record ListItemsRequest
{
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 20;
public string? Category { get; init; }
}
/// <summary>
/// Response model for listing inventory items.
/// </summary>
public sealed record ListItemsResponse
{
public required List<InventoryItem> Items { get; init; }
public required int TotalCount { get; init; }
public required int Page { get; init; }
public required int PageSize { get; init; }
}
/// <summary>
/// Inventory item model.
/// </summary>
public sealed record InventoryItem
{
public required string Sku { get; init; }
public required string Name { get; init; }
public required string Category { get; init; }
public required int QuantityOnHand { get; init; }
public required decimal UnitPrice { get; init; }
}
/// <summary>
/// Endpoint for listing inventory items.
/// Demonstrates pagination and filtering.
/// </summary>
[StellaEndpoint("GET", "/items", TimeoutSeconds = 15)]
public sealed class ListItemsEndpoint : IStellaEndpoint<ListItemsRequest, ListItemsResponse>
{
private readonly ILogger<ListItemsEndpoint> _logger;
public ListItemsEndpoint(ILogger<ListItemsEndpoint> logger)
{
_logger = logger;
}
public Task<ListItemsResponse> HandleAsync(
ListItemsRequest request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Listing inventory items - Page: {Page}, PageSize: {PageSize}, Category: {Category}",
request.Page,
request.PageSize,
request.Category ?? "(all)");
// Simulate item list
var items = new List<InventoryItem>
{
new()
{
Sku = "SKU-001",
Name = "Widget A",
Category = "widgets",
QuantityOnHand = 100,
UnitPrice = 9.99m
},
new()
{
Sku = "SKU-002",
Name = "Widget B",
Category = "widgets",
QuantityOnHand = 50,
UnitPrice = 14.99m
},
new()
{
Sku = "SKU-003",
Name = "Gadget X",
Category = "gadgets",
QuantityOnHand = 25,
UnitPrice = 29.99m
}
};
// Filter by category if specified
if (!string.IsNullOrWhiteSpace(request.Category))
{
items = items.Where(i =>
i.Category.Equals(request.Category, StringComparison.OrdinalIgnoreCase)).ToList();
}
return Task.FromResult(new ListItemsResponse
{
Items = items,
TotalCount = items.Count,
Page = request.Page,
PageSize = request.PageSize
});
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.0-rc.2.25502.107" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Microservice\StellaOps.Microservice.csproj" />
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Router.Common\StellaOps.Router.Common.csproj" />
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Router.Transport.InMemory\StellaOps.Router.Transport.InMemory.csproj" />
<!-- Reference the source generator -->
<ProjectReference Include="..\..\..\..\src\__Libraries\StellaOps.Microservice.SourceGen\StellaOps.Microservice.SourceGen.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,38 @@
using Examples.Inventory.Microservice.Endpoints;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StellaOps.Microservice;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Transport.InMemory;
var builder = Host.CreateApplicationBuilder(args);
// Configure the Stella microservice
builder.Services.AddStellaMicroservice(options =>
{
options.ServiceName = "inventory";
options.Version = "1.0.0";
options.Region = "demo";
options.InstanceId = $"inventory-{Environment.MachineName}";
options.Routers =
[
new RouterEndpointConfig
{
Host = "localhost",
Port = 5100,
TransportType = TransportType.InMemory
}
];
});
// Register endpoint handlers
builder.Services.AddScoped<ListItemsEndpoint>();
builder.Services.AddScoped<GetItemEndpoint>();
// Add in-memory transport
builder.Services.AddInMemoryTransport();
var host = builder.Build();
Console.WriteLine("Inventory microservice starting...");
await host.RunAsync();

View File

@@ -0,0 +1,76 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using FluentAssertions;
using Xunit;
namespace Examples.Integration.Tests;
/// <summary>
/// Integration tests for the Billing microservice endpoints.
/// </summary>
public sealed class BillingEndpointTests : IClassFixture<GatewayFixture>
{
private readonly GatewayFixture _fixture;
public BillingEndpointTests(GatewayFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task CreateInvoice_WithValidRequest_ReturnsCreatedInvoice()
{
// Arrange
var request = new
{
customerId = "CUST-001",
amount = 99.99m,
description = "Test invoice"
};
// Act
var response = await _fixture.GatewayClient.PostAsJsonAsync("/invoices", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain("invoiceId");
}
[Fact]
public async Task GetInvoice_WithValidId_ReturnsInvoice()
{
// Arrange
var invoiceId = "INV-12345";
// Act
var response = await _fixture.GatewayClient.GetAsync($"/invoices/{invoiceId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain(invoiceId);
}
[Fact]
public async Task UploadAttachment_WithStreamingData_ReturnsSuccess()
{
// Arrange
var invoiceId = "INV-12345";
var attachmentData = Encoding.UTF8.GetBytes("This is test attachment content");
using var content = new ByteArrayContent(attachmentData);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
// Act
var response = await _fixture.GatewayClient.PostAsync(
$"/invoices/{invoiceId}/attachments",
content);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseContent = await response.Content.ReadAsStringAsync();
responseContent.Should().Contain("attachmentId");
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Examples.Gateway\Examples.Gateway.csproj" />
<ProjectReference Include="..\..\src\Examples.Billing.Microservice\Examples.Billing.Microservice.csproj" />
<ProjectReference Include="..\..\src\Examples.Inventory.Microservice\Examples.Inventory.Microservice.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,114 @@
using Examples.Billing.Microservice.Endpoints;
using Examples.Inventory.Microservice.Endpoints;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StellaOps.Microservice;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Transport.InMemory;
using Xunit;
namespace Examples.Integration.Tests;
/// <summary>
/// Test fixture that sets up the gateway and microservices for integration testing.
/// Uses in-memory transport for fast, isolated tests.
/// </summary>
public sealed class GatewayFixture : IAsyncLifetime
{
private WebApplicationFactory<Examples.Gateway.Program>? _gatewayFactory;
private IHost? _billingHost;
private IHost? _inventoryHost;
public HttpClient GatewayClient { get; private set; } = null!;
public async Task InitializeAsync()
{
// Start the gateway
_gatewayFactory = new WebApplicationFactory<Examples.Gateway.Program>()
.WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Testing");
builder.ConfigureServices(services =>
{
services.AddInMemoryTransport();
});
});
GatewayClient = _gatewayFactory.CreateClient();
// Start billing microservice
var billingBuilder = Host.CreateApplicationBuilder();
billingBuilder.Services.AddStellaMicroservice(options =>
{
options.ServiceName = "billing";
options.Version = "1.0.0";
options.Region = "test";
options.InstanceId = "billing-test";
options.Routers =
[
new RouterEndpointConfig
{
Host = "localhost",
Port = 5100,
TransportType = TransportType.InMemory
}
];
});
billingBuilder.Services.AddScoped<CreateInvoiceEndpoint>();
billingBuilder.Services.AddScoped<GetInvoiceEndpoint>();
billingBuilder.Services.AddScoped<UploadAttachmentEndpoint>();
billingBuilder.Services.AddInMemoryTransport();
_billingHost = billingBuilder.Build();
await _billingHost.StartAsync();
// Start inventory microservice
var inventoryBuilder = Host.CreateApplicationBuilder();
inventoryBuilder.Services.AddStellaMicroservice(options =>
{
options.ServiceName = "inventory";
options.Version = "1.0.0";
options.Region = "test";
options.InstanceId = "inventory-test";
options.Routers =
[
new RouterEndpointConfig
{
Host = "localhost",
Port = 5100,
TransportType = TransportType.InMemory
}
];
});
inventoryBuilder.Services.AddScoped<ListItemsEndpoint>();
inventoryBuilder.Services.AddScoped<GetItemEndpoint>();
inventoryBuilder.Services.AddInMemoryTransport();
_inventoryHost = inventoryBuilder.Build();
await _inventoryHost.StartAsync();
// Allow services to register
await Task.Delay(100);
}
public async Task DisposeAsync()
{
GatewayClient.Dispose();
if (_billingHost is not null)
{
await _billingHost.StopAsync();
_billingHost.Dispose();
}
if (_inventoryHost is not null)
{
await _inventoryHost.StopAsync();
_inventoryHost.Dispose();
}
_gatewayFactory?.Dispose();
}
}

View File

@@ -0,0 +1,74 @@
using System.Net;
using System.Text.Json;
using FluentAssertions;
using Xunit;
namespace Examples.Integration.Tests;
/// <summary>
/// Integration tests for the Inventory microservice endpoints.
/// </summary>
public sealed class InventoryEndpointTests : IClassFixture<GatewayFixture>
{
private readonly GatewayFixture _fixture;
public InventoryEndpointTests(GatewayFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task ListItems_WithoutFilters_ReturnsAllItems()
{
// Act
var response = await _fixture.GatewayClient.GetAsync("/items");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain("items");
content.Should().Contain("totalCount");
}
[Fact]
public async Task ListItems_WithCategoryFilter_ReturnsFilteredItems()
{
// Act
var response = await _fixture.GatewayClient.GetAsync("/items?category=widgets");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain("widgets");
}
[Fact]
public async Task ListItems_WithPagination_ReturnsPaginatedResponse()
{
// Act
var response = await _fixture.GatewayClient.GetAsync("/items?page=1&pageSize=10");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain("\"page\":1");
content.Should().Contain("\"pageSize\":10");
}
[Fact]
public async Task GetItem_WithValidSku_ReturnsItem()
{
// Arrange
var sku = "SKU-001";
// Act
var response = await _fixture.GatewayClient.GetAsync($"/items/{sku}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain(sku);
content.Should().Contain("name");
content.Should().Contain("quantityOnHand");
}
}

View File

@@ -0,0 +1,79 @@
using System.Net;
using FluentAssertions;
using Xunit;
namespace Examples.Integration.Tests;
/// <summary>
/// Tests that verify multiple microservices can register and receive
/// correctly routed requests through the gateway.
/// </summary>
public sealed class MultiServiceRoutingTests : IClassFixture<GatewayFixture>
{
private readonly GatewayFixture _fixture;
public MultiServiceRoutingTests(GatewayFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task Gateway_RoutesBillingRequests_ToBillingService()
{
// Act
var response = await _fixture.GatewayClient.GetAsync("/invoices/INV-001");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain("INV-001");
}
[Fact]
public async Task Gateway_RoutesInventoryRequests_ToInventoryService()
{
// Act
var response = await _fixture.GatewayClient.GetAsync("/items/SKU-001");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
content.Should().Contain("SKU-001");
}
[Fact]
public async Task Gateway_HandlesSequentialRequestsToDifferentServices()
{
// Act - Send requests to both services
var billingResponse = await _fixture.GatewayClient.GetAsync("/invoices/INV-001");
var inventoryResponse = await _fixture.GatewayClient.GetAsync("/items/SKU-001");
// Assert - Both should succeed
billingResponse.StatusCode.Should().Be(HttpStatusCode.OK);
inventoryResponse.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task Gateway_HandlesConcurrentRequestsToDifferentServices()
{
// Act - Send requests to both services concurrently
var billingTask = _fixture.GatewayClient.GetAsync("/invoices/INV-001");
var inventoryTask = _fixture.GatewayClient.GetAsync("/items/SKU-001");
await Task.WhenAll(billingTask, inventoryTask);
// Assert - Both should succeed
billingTask.Result.StatusCode.Should().Be(HttpStatusCode.OK);
inventoryTask.Result.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task Gateway_ReturnsNotFound_ForUnknownRoute()
{
// Act
var response = await _fixture.GatewayClient.GetAsync("/unknown/route");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}