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>
50 changes: 50 additions & 0 deletions Api.Gateway/LoadBalancer/WeightedRandom.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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 section = configuration.GetSection("LoadBalancer:WeightedRandom:Weights");

if (!section.Exists())
{
throw new InvalidOperationException(
$"Required configuration section '{section.Path}' was not found. " +
"Please check your appsettings.json or environment variables.");
}

var frequencies = section.Get<int[]>();
if (frequencies == null || frequencies.Length == 0)
{
throw new InvalidOperationException(
$"Configuration section '{section.Path}' exists but contains no values.");
}
_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) { }
}
33 changes: 33 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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:54707",
"sslPort": 44338
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5124",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7185;http://localhost:5124",
"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": "/training-course",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/training-course",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 4000 },
{ "Host": "localhost", "Port": 4001 },
{ "Host": "localhost", "Port": 4002 },
{ "Host": "localhost", "Port": 4003 },
{ "Host": "localhost", "Port": 4004 }
],
"LoadBalancerOptions": {
"Type": "WeightedRandom"
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:7185"
}
}
33 changes: 33 additions & 0 deletions AspireApp/AspireApp.AppHost.Tests/AspireApp.AppHost.Tests.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.AppHost\AspireApp.AppHost.csproj" />
<ProjectReference Include="..\..\Service.Api\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>
93 changes: 93 additions & 0 deletions AspireApp/AspireApp.AppHost.Tests/IntegrationTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using Aspire.Hosting;
using Microsoft.Extensions.Logging;
using Service.Api.Entities;
using System.Text.Json;
using Xunit.Abstractions;

namespace AspireApp.AppHost.Tests;

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

/// <inheritdoc/>
public async Task InitializeAsync()
{
var cancellationToken = CancellationToken.None;
IDistributedApplicationTestingBuilder 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>
/// Проверяет, что вызов гейтвея возвращает сгенерированный учебный курс
/// и тот же курс через брокер попадает в Minio в виде файла
/// </summary>
[Fact]
public async Task TestPipeline_CourseIsReturnedAndStoredInMinio()
{
var random = new Random();
var id = random.Next(1, 1000);

using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http");
using var gatewayResponse = await gatewayClient.GetAsync($"/training-course?id={id}");
var apiCourse = JsonSerializer.Deserialize<TrainingCourse>(await gatewayResponse.Content.ReadAsStringAsync());

await Task.Delay(5000);

using var fileServiceClient = _app!.CreateHttpClient("file-service", "http");
using var listResponse = await fileServiceClient.GetAsync("/api/s3");
var fileList = JsonSerializer.Deserialize<List<string>>(await listResponse.Content.ReadAsStringAsync());

using var fileResponse = await fileServiceClient.GetAsync($"/api/s3/training_course_{id}.json");
var storedCourse = JsonSerializer.Deserialize<TrainingCourse>(await fileResponse.Content.ReadAsStringAsync());

Assert.NotNull(fileList);
Assert.NotNull(apiCourse);
Assert.NotNull(storedCourse);
Assert.Equal(id, storedCourse.Id);
Assert.Equivalent(apiCourse, storedCourse);
}

/// <summary>
/// Проверяет, что повторный запрос того же курса возвращает идентичный результат
/// </summary>
[Fact]
public async Task TestPipeline_RepeatedRequestReturnsCachedCourse()
{
var random = new Random();
var id = random.Next(1001, 2000);

using var gatewayClient = _app!.CreateHttpClient("api-gateway", "http");

using var firstResponse = await gatewayClient.GetAsync($"/training-course?id={id}");
var firstCourse = JsonSerializer.Deserialize<TrainingCourse>(await firstResponse.Content.ReadAsStringAsync());

using var secondResponse = await gatewayClient.GetAsync($"/training-course?id={id}");
var secondCourse = JsonSerializer.Deserialize<TrainingCourse>(await secondResponse.Content.ReadAsStringAsync());

Assert.NotNull(firstCourse);
Assert.NotNull(secondCourse);
Assert.Equal(id, firstCourse.Id);
Assert.Equivalent(firstCourse, secondCourse);
}

/// <inheritdoc/>
public async Task DisposeAsync()
{
await _app!.StopAsync();
await _app.DisposeAsync();
}
}
34 changes: 34 additions & 0 deletions AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<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>3cec140f-e46f-4c50-ade0-6bd5134c5831</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.2" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.5.2" />
<PackageReference Include="CommunityToolkit.Aspire.Hosting.Minio" Version="9.9.0" />
<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="..\..\File.Service\File.Service.csproj" />
<ProjectReference Include="..\..\Service.Api\Service.Api.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="CloudFormation\training-course-template.yaml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Cloud formation template for training course project (SNS + Minio variant)'

Parameters:
TopicName:
Type: String
Description: Name for the SNS topic
Default: 'training-course-topic'

Resources:
TrainingCourseTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Ref TopicName
DisplayName: !Ref TopicName
Tags:
- Key: Name
Value: !Ref TopicName
- Key: Environment
Value: Sample

Outputs:
SNSTopicName:
Description: Name of the SNS topic
Value: !GetAtt TrainingCourseTopic.TopicName

SNSTopicArn:
Description: ARN of the SNS topic
Value: !Ref TrainingCourseTopic
Loading
Loading