Skip to content
Closed
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
15 changes: 15 additions & 0 deletions Api.Gateway/Api.Gateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Ocelot" Version="24.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AspireApp\AspireApp.ServiceDefaults\AspireApp.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
36 changes: 36 additions & 0 deletions Api.Gateway/LoadBalancer/WeightedRandom.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway.LoadBalancer;

/// <summary>
/// Балансировка случайным образом с весами
/// </summary>
public class WeightedRandom : ILoadBalancer
{
private readonly Func<Task<List<Service>>> _services = null!;
private static readonly object _locker = new();

private readonly int[] _values = null!;

public string Type => nameof(WeightedRandom);
public WeightedRandom(Func<Task<List<Service>>> services, IConfiguration configuration)
{
_services = services;
var frequencies = configuration.GetSection("LoadBalancer:WeightedRandom:Weights").Get<int[]>();
if (frequencies == null || frequencies.Length == 0)
throw new InvalidOperationException("Weights is empty or null. Add weights to configuration");
_values = [.. Enumerable.Range(0, frequencies.Length).Zip(frequencies, (val, freq) => Enumerable.Repeat(val, freq)).SelectMany(x => x)];
}
public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext)
{
var services = await _services.Invoke();
lock (_locker)
{
Random.Shared.Shuffle(_values);
return new OkResponse<ServiceHostAndPort>(services[_values.First()].HostAndPort);
}
}
public void Release(ServiceHostAndPort hostAndPort) { }
}
29 changes: 29 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Api.Gateway.LoadBalancer;
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.Services.AddOcelot()
.AddCustomLoadBalancer<WeightedRandom>((serviceProvider, _, discoveryProvider) =>
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
return new WeightedRandom(discoveryProvider.GetAsync, configuration);
});


builder.Services.AddCors(options => options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("https://localhost:5127", "http://localhost:5127", "https://localhost:7282")
.WithMethods("GET")
.AllowAnyHeader();
}));

var app = builder.Build();
app.UseCors();
await app.UseOcelot();
app.Run();
38 changes: 38 additions & 0 deletions Api.Gateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:42987",
"sslPort": 44379
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5086",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7099;http://localhost:5086",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
8 changes: 8 additions & 0 deletions Api.Gateway/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
14 changes: 14 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"LoadBalancer": {
"WeightedRandom": {
"Weights": [ 1, 2, 3, 2, 1 ]
}
}
}
23 changes: 23 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/employee",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/employee",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 7170 },
{ "Host": "localhost", "Port": 7171 },
{ "Host": "localhost", "Port": 7172 },
{ "Host": "localhost", "Port": 7173 },
{ "Host": "localhost", "Port": 7174 }
],
"LoadBalancerOptions": {
"Type": "WeightedRandom"
}
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7099"
}
}
33 changes: 33 additions & 0 deletions AspireApp.AppHost.Test/AspireApp.AppHost.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.Testing" Version="9.5.2" />
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="MartinCostello.Logging.XUnit" Version="0.7.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\AspireApp\AspireApp.AppHost\AspireApp.AppHost.csproj" />
<ProjectReference Include="..\ServiceApi\Service.Api.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="System.Net" />
<Using Include="Microsoft.Extensions.DependencyInjection" />
<Using Include="Aspire.Hosting.ApplicationModel" />
<Using Include="Aspire.Hosting.Testing" />
<Using Include="Xunit" />
</ItemGroup>

</Project>
76 changes: 76 additions & 0 deletions AspireApp.AppHost.Test/IntegrationTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using Aspire.Hosting;
using Microsoft.Extensions.Logging;
using Service.Api.Entities;
using System.Text.Json;
using Xunit.Abstractions;

namespace AspireApp.AppHost.Test;

/// <summary>
/// Интеграционные тесты для проверки микросервисного пайплайна
/// </summary>
/// <param name="output">Служба журналирования юнит-тестов</param>
public class IntegrationTests(ITestOutputHelper output) : IAsyncLifetime
{
private DistributedApplication? _app;

/// <inheritdoc/>
public async Task InitializeAsync()
{
var cancellationToken = CancellationToken.None;
var builder = await DistributedApplicationTestingBuilder.CreateAsync<Projects.AspireApp_AppHost>(cancellationToken);
builder.Configuration["DcpPublisher:RandomizePorts"] = "false";
builder.Services.AddLogging(logging =>
{
logging.AddXUnit(output);
logging.SetMinimumLevel(LogLevel.Debug);
logging.AddFilter("Aspire.Hosting.Dcp", LogLevel.Debug);
logging.AddFilter("Aspire.Hosting", LogLevel.Debug);
});

_app = await builder.BuildAsync(cancellationToken);
await _app.StartAsync(cancellationToken);
}

/// <summary>
/// Проверяет, что вызов гейтвея:
/// <list type="bullet">
/// <item><description>В ответ отправляет сгенерированного сотрудника</description></item>
/// <item><description>Сериализует сотрудника в S3 хранилище</description></item>
/// <item><description>Проверяет, что данные из предыдущих пунктов идентичны</description></item>
/// </list>
/// </summary>
[Fact]
public async Task TestPipeline()
{
var random = new Random();
var id = random.Next(1, 100);
using var gatewayClient = _app.CreateHttpClient("employee-api-gateway", "http");
using var gatewayResponse = await gatewayClient!.GetAsync($"/employee?id={id}");
var apiEmployee = JsonSerializer.Deserialize<Employee>(await gatewayResponse.Content.ReadAsStringAsync());

await Task.Delay(5000);
using var sinkClient = _app.CreateHttpClient("employee-sink", "http");
using var listResponse = await sinkClient!.GetAsync($"/api/s3");
var employeeList = JsonSerializer.Deserialize<List<string>>(await listResponse.Content.ReadAsStringAsync());
using var s3Response = await sinkClient!.GetAsync($"/api/s3/employee_{id}.json");
var s3Employee = JsonSerializer.Deserialize<Employee>(await s3Response.Content.ReadAsStringAsync());

Assert.NotNull(employeeList);
Assert.Single(employeeList);
Assert.NotNull(apiEmployee);
Assert.NotNull(s3Employee);
Assert.Equal(id, s3Employee.Id);
Assert.Equivalent(apiEmployee, s3Employee);
}

/// <inheritdoc/>
public async Task DisposeAsync()
{
if (_app is not null)
{
await _app.StopAsync();
await _app.DisposeAsync();
}
}
}
57 changes: 57 additions & 0 deletions AspireApp/AspireApp.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using Amazon;
using Aspire.Hosting.LocalStack.Container;

var builder = DistributedApplication.CreateBuilder(args);

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

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

var awsConfig = builder.AddAWSSDKConfig()
.WithProfile("default")
.WithRegion(RegionEndpoint.EUCentral1);

var localstack = builder
.AddLocalStack("employee-localstack", awsConfig: awsConfig, configureContainer: container =>
{
container.Lifetime = ContainerLifetime.Session;
container.DebugLevel = 1;
container.LogLevel = LocalStackLogLevel.Debug;
container.Port = 4566;
container.AdditionalEnvironmentVariables
.Add("DEBUG", "1");
container.AdditionalEnvironmentVariables
.Add("SNS_CERT_URL_HOST", "sns.eu-central-1.amazonaws.com");
});

var cloudFormationTemplate = "CloudFormation/employee-template-sns-s3.yaml";
var awsResources = builder.AddAWSCloudFormationTemplate("resources", cloudFormationTemplate, "employee")
.WithReference(awsConfig);

for (var i = 0; i < 5; i++)
{
var service = builder.AddProject<Projects.Service_Api>($"employee-api-{i + 1}", launchProfileName: null)
.WithHttpsEndpoint(7170 + i)
.WithReference(cache, "RedisCache")
.WithReference(awsResources)
.WithEnvironment("Settings__MessageBroker", "SNS")
.WaitFor(cache)
.WaitFor(awsResources);
gateway.WaitFor(service);
}

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

var sink = builder.AddProject<Projects.Event_Sink>("employee-sink")
.WithReference(awsResources)
.WithEnvironment("Settings__MessageBroker", "SNS")
.WithEnvironment("Settings__S3Hosting", "Localstack")
.WaitFor(awsResources);

sink.WithEnvironment("AWS__Resources__SNSUrl", "http://host.docker.internal:5134/api/sns");

builder.UseLocalStack(localstack);

builder.Build().Run();
33 changes: 33 additions & 0 deletions AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<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>
<UserSecretsId>8acee786-1688-40c1-943e-5186ce386476</UserSecretsId>
</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="..\..\Api.Gateway\Api.Gateway.csproj" />
<ProjectReference Include="..\..\Client.Wasm\Client.Wasm.csproj" />
<ProjectReference Include="..\..\Event.Sink\Event.Sink.csproj" />
<ProjectReference Include="..\..\ServiceApi\Service.Api.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="CloudFormation\employee-template-sns-s3.yaml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Loading