Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions ApiGateway/ApiGateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>ApiGateway</AssemblyName>
<RootNamespace>ApiGateway</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Ocelot" Version="24.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\AspireApp\AspireApp.ServiceDefaults\AspireApp.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="ocelot.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
16 changes: 16 additions & 0 deletions ApiGateway/Configuration/WeightedRoundRobinOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace ApiGateway.Configuration;

public sealed class WeightedRoundRobinOptions
{
public const string SectionName = "WeightedRoundRobin";

public List<ReplicaNodeOptions> Nodes { get; init; } = new();
}

public sealed class ReplicaNodeOptions
{
public string Host { get; init; } = string.Empty;
public int Port { get; init; }
public int Weight { get; init; } = 1;
public string ReplicaId { get; init; } = string.Empty;
}
72 changes: 72 additions & 0 deletions ApiGateway/LoadBalancing/WeightedRoundRobinBalancer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using ApiGateway.Configuration;
using Microsoft.Extensions.Options;
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace ApiGateway.LoadBalancing;

public sealed class WeightedRoundRobinBalancer : ILoadBalancer
{
private static readonly object Sync = new();
private readonly ILogger<WeightedRoundRobinBalancer> _logger;
private readonly List<ServiceHostAndPort> _rotation;
private int _currentIndex;

public WeightedRoundRobinBalancer(
IOptions<WeightedRoundRobinOptions> options,
ILogger<WeightedRoundRobinBalancer> logger)
{
_logger = logger;
_rotation = BuildRotation(options.Value.Nodes);

if (_rotation.Count == 0)
{
throw new InvalidOperationException("Не настроены узлы для Weighted Round Robin балансировки.");
}
}

public string Type => nameof(WeightedRoundRobinBalancer);

public Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext context)
{
lock (Sync)
{
if (_currentIndex >= _rotation.Count)
{
_currentIndex = 0;
}

var next = _rotation[_currentIndex++];

_logger.LogInformation(
"Gateway routed request to {ReplicaAddress} by {BalancerType}",
next,
Type);

return Task.FromResult<Response<ServiceHostAndPort>>(
new OkResponse<ServiceHostAndPort>(next));
}
}

public void Release(ServiceHostAndPort hostAndPort)
{
}

private static List<ServiceHostAndPort> BuildRotation(IEnumerable<ReplicaNodeOptions> nodes)
{
var rotation = new List<ServiceHostAndPort>();

foreach (var node in nodes.Where(static n => !string.IsNullOrWhiteSpace(n.Host) && n.Port > 0))
{
var normalizedWeight = Math.Max(1, node.Weight);

for (var i = 0; i < normalizedWeight; i++)
{
rotation.Add(new ServiceHostAndPort(node.Host, node.Port));
}
}

return rotation;
}
}
43 changes: 43 additions & 0 deletions ApiGateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using ApiGateway.Configuration;
using ApiGateway.LoadBalancing;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Services.AddServiceDiscovery();
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole(options =>
{
options.IncludeScopes = true;
options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ ";
});

builder.Services.Configure<WeightedRoundRobinOptions>(
builder.Configuration.GetSection(WeightedRoundRobinOptions.SectionName));

builder.Services.AddOcelot(builder.Configuration)
.AddCustomLoadBalancer<WeightedRoundRobinBalancer>(sp =>
new WeightedRoundRobinBalancer(
sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<WeightedRoundRobinOptions>>(),
sp.GetRequiredService<ILogger<WeightedRoundRobinBalancer>>()));

builder.Services.AddCors(options => options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(["http://localhost:5127", "https://localhost:7282"]);
policy.WithMethods("GET");
policy.WithHeaders("Content-Type");
policy.WithExposedHeaders("X-Service-Replica", "X-Service-Weight");
}));

var app = builder.Build();

app.UseCors();
app.MapDefaultEndpoints();

await app.UseOcelot();

app.Run();
14 changes: 14 additions & 0 deletions ApiGateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:7200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
9 changes: 9 additions & 0 deletions ApiGateway/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Ocelot": "Information"
}
}
}
10 changes: 10 additions & 0 deletions ApiGateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Ocelot": "Information"
}
},
"AllowedHosts": "*"
}
41 changes: 41 additions & 0 deletions ApiGateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/employee",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/employee",
"DownstreamScheme": "https",
"LoadBalancerOptions": {
"Type": "WeightedRoundRobinBalancer"
},
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 15000 },
{ "Host": "localhost", "Port": 15001 },
{ "Host": "localhost", "Port": 15002 },
{ "Host": "localhost", "Port": 15003 },
{ "Host": "localhost", "Port": 15004 }
]
},
{
"UpstreamPathTemplate": "/files/{id}",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/files/{id}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 16000 }
]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:7200"
},
"WeightedRoundRobin": {
"Nodes": [
{ "ReplicaId": "R1", "Host": "localhost", "Port": 15000, "Weight": 1 },
{ "ReplicaId": "R2", "Host": "localhost", "Port": 15001, "Weight": 2 },
{ "ReplicaId": "R3", "Host": "localhost", "Port": 15002, "Weight": 3 },
{ "ReplicaId": "R4", "Host": "localhost", "Port": 15003, "Weight": 2 },
{ "ReplicaId": "R5", "Host": "localhost", "Port": 15004, "Weight": 1 }
]
}
}
77 changes: 77 additions & 0 deletions AspireApp/AspireApp.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using Aspire.Hosting.LocalStack;

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("employee-cache")
.WithRedisInsight(containerName: "employee-insight");

// LocalStack поднимаем через интеграцию LocalStack.Aspire.Hosting — Aspire управляет
// жизненным циклом контейнера. Закрепляем версию 3.5: в 3.7.2+ есть известный баг
// с подтверждением HTTP SNS-подписок (https://github.com/localstack/localstack/issues/11652).
var localstack = builder.AddLocalStack("localstack", configureContainer: container =>
{
container.Lifetime = ContainerLifetime.Session;
container.DebugLevel = 1;
container.ContainerImageTag = "3.5";
})
?? throw new InvalidOperationException(
"LocalStack отключён в конфигурации AppHost (LocalStack:UseLocalStack = false). " +
"Включите его в appsettings.json, иначе file-service и service-api не получат своего edge-эндпойнта.");

// LocalStack.Aspire.Hosting всегда проксирует edge-порт 4566 через случайный хостовый порт,
// поэтому ServiceURL приходится резолвить динамически — иначе AWS-клиенты на хосте промахнутся.
// ILocalStackResource не реализует IResourceWithEndpoints напрямую, но под капотом это
// ContainerResource — приводим к нему, чтобы можно было дотянуться до edge-эндпойнта.
var localstackContainer = (IResourceBuilder<ContainerResource>)(object)localstack;
var localstackHttp = localstackContainer.GetEndpoint("http");
var localstackEndpoint = ReferenceExpression.Create(
$"http://localhost:{localstackHttp.Property(EndpointProperty.Port)}");

var gateway = builder.AddProject<Projects.ApiGateway>("api-gateway");

var replicaWeights = new[] { 1, 2, 3, 2, 1 };

const int fileServicePort = 16000;

// WaitFor(localstack) не используем: health-check интеграции бывает «unhealthy» дольше,
// чем нужно, и блокирует старт зависимых сервисов. SnsFileExportWorker и SnsEmployeeEventPublisher
// уже имеют retry-цикл и сами дождутся готовности LocalStack.
var fileService = builder.AddProject<Projects.File_Service>("file-service", launchProfileName: null)
.WithHttpEndpoint(port: fileServicePort, name: "http")
.WithEnvironment("Aws__ServiceUrl", localstackEndpoint)
.WithEnvironment("Aws__Region", "us-east-1")
.WithEnvironment("Aws__AccessKey", "test")
.WithEnvironment("Aws__SecretKey", "test")
.WithEnvironment("Aws__TopicName", "employee-generated-topic")
.WithEnvironment("Aws__BucketName", "employee-files");

// NotificationEndpoint собираем уже после описания endpoint, чтобы порт
// можно было резолвить динамически (важно для Aspire.Testing,
// где фиксированный 16000 может быть переопределён).
var fileServiceHttp = fileService.GetEndpoint("http");
fileService.WithEnvironment("Aws__NotificationEndpoint", ReferenceExpression.Create(
$"http://host.docker.internal:{fileServiceHttp.Property(EndpointProperty.Port)}/sns/notifications"));

for (var i = 0; i < 5; i++)
{
var service = builder.AddProject<Projects.Service_Api>($"service-api-{i}", launchProfileName: null)
.WithHttpsEndpoint(port: 15000 + i)
.WithReference(cache, "RedisCache")
.WithEnvironment("ReplicaId", "R" + (i + 1))
.WithEnvironment("ReplicaWeight", replicaWeights[i].ToString())
.WithEnvironment("Aws__ServiceUrl", localstackEndpoint)
.WithEnvironment("Aws__Region", "us-east-1")
.WithEnvironment("Aws__AccessKey", "test")
.WithEnvironment("Aws__SecretKey", "test")
.WithEnvironment("Aws__TopicName", "employee-generated-topic")
.WaitFor(cache);

gateway.WaitFor(service);
}

gateway.WaitFor(fileService);

builder.AddProject<Projects.Client_Wasm>("employee")
.WaitFor(gateway);

builder.Build().Run();
26 changes: 26 additions & 0 deletions AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<Sdk Name="Aspire.AppHost.Sdk" Version="9.5.2" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.2" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.5.2" />
<PackageReference Include="LocalStack.Aspire.Hosting" Version="9.5.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\ApiGateway\ApiGateway.csproj" />
<ProjectReference Include="..\..\Client.Wasm\Client.Wasm.csproj" />
<ProjectReference Include="..\..\FileService\File.Service.csproj" />
<ProjectReference Include="..\..\ServiceApi\Service.Api.csproj" />
</ItemGroup>

</Project>
32 changes: 32 additions & 0 deletions AspireApp/AspireApp.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17096;http://localhost:15155",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21139",
"DOTNET_DASHBOARD_OTLP_HTTP_ENDPOINT_URL": "https://localhost:21140",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22017"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15155",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19197",
"DOTNET_DASHBOARD_OTLP_HTTP_ENDPOINT_URL": "http://localhost:19198",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20116"
}
}
}
}
Loading