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

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

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

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

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

namespace Api.Gateway.LoadBalancers;

/// <summary>
/// Балансировщик нагрузки на основе взвешенного случайного выбора (Weighted Random).
/// Каждой реплике назначается вероятность выбора. При поступлении запроса реплика выбирается случайно с учётом заданных вероятностей
/// </summary>
/// <param name="services">Фабрика для получения списка доступных сервисов</param>
/// <param name="configuration">Конфигурация приложения</param>
public class WeightedRandomLoadBalancer(Func<Task<List<Service>>> services, IConfiguration configuration)
: ILoadBalancer
{
private readonly double[] _cumulativeWeights = BuildCumulativeWeights(
configuration.GetSection("WeightedRandomWeights").Get<double[]>() ?? [0.4, 0.3, 0.15, 0.1, 0.05]);

public string Type => nameof(WeightedRandomLoadBalancer);

public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext)
{
var availableServices = await services();

if (availableServices.Count == 0)
throw new InvalidOperationException("No available downstream services");

var index = Array.BinarySearch(_cumulativeWeights, Random.Shared.NextDouble());
if (index < 0) index = ~index;

return new OkResponse<ServiceHostAndPort>(
availableServices[Math.Min(index, availableServices.Count - 1)].HostAndPort);
}

public void Release(ServiceHostAndPort hostAndPort) { }

/// <summary>
/// Строит массив кумулятивных весов на основе входных весов
/// </summary>
/// <param name="weights">Веса</param>
/// <returns>Каждый элемент результирующего массива равен сумме всех предыдущих весов включительно</returns>
private static double[] BuildCumulativeWeights(double[] weights)
{
var total = weights.Sum();
var cumulative = new double[weights.Length];
cumulative[0] = weights[0] / total;
for (var i = 1; i < weights.Length; i++)
cumulative[i] = cumulative[i - 1] + weights[i] / total;
return cumulative;
}
}
34 changes: 34 additions & 0 deletions API.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Api.Gateway.LoadBalancers;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddPolicy("LocalPolicy", policy =>
{
policy
.SetIsOriginAllowed(origin => origin.StartsWith("https://localhost"))
.WithHeaders("Content-Type")
.WithMethods("GET");
});
});

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

builder.Services
.AddOcelot(builder.Configuration)
.AddCustomLoadBalancer((sp, _, discoveryProvider) =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
return new WeightedRandomLoadBalancer(discoveryProvider.GetAsync, configuration);
});

var app = builder.Build();

app.UseCors("LocalPolicy");
await app.UseOcelot();

await app.RunAsync();
23 changes: 23 additions & 0 deletions API.Gateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5296",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7270;http://localhost:5296",
"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"
}
}
}
10 changes: 10 additions & 0 deletions API.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"WeightedRandomWeights": [ 0.30, 0.25, 0.20, 0.15, 0.10 ]
}
36 changes: 36 additions & 0 deletions API.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/employee",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/employee",
"DownstreamScheme": "https",
"LoadBalancerOptions": {
"Type": "WeightedRandomLoadBalancer"
},
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8000
},
{
"Host": "localhost",
"Port": 8001
},
{
"Host": "localhost",
"Port": 8002
},
{
"Host": "localhost",
"Port": 8003
},
{
"Host": "localhost",
"Port": 8004
}
]
}
]
}

6 changes: 3 additions & 3 deletions Client.Wasm/Client.Wasm.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand All @@ -14,8 +14,8 @@
<PackageReference Include="Blazorise" Version="1.8.8" />
<PackageReference Include="Blazorise.Bootstrap" Version="1.8.8" />
<PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.8.8" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.22" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.22" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="10.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="10.0.7" PrivateAssets="all" />
</ItemGroup>

</Project>
8 changes: 4 additions & 4 deletions Client.Wasm/Components/StudentCard.razor
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
</CardHeader>
<CardBody>
<UnorderedList Unstyled>
<UnorderedListItem>Номер <Strong>№X "Название лабораторной"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№Х "Название варианта"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Фамилией Именем 65ХХ</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://puginarug.com/">Ссылка на форк</Link></UnorderedListItem>
<UnorderedListItem>Номер <Strong>№3 "Интеграционное тестирование"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№48 "SQS, Minio"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Ненашевым Дмитрием 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/neygenius/cloud-development/">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
2 changes: 1 addition & 1 deletion Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
"BaseAddress": ""
"BaseAddress": "https://localhost:7270/employee"
}
22 changes: 22 additions & 0 deletions Cloud.API/Cloud.API.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="13.3.0" />
<PackageReference Include="AWSSDK.SQS" Version="4.0.2.28" />
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="LocalStack.Client" Version="2.0.0" />
<PackageReference Include="LocalStack.Client.Extensions" Version="2.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
</ItemGroup>

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

</Project>
39 changes: 39 additions & 0 deletions Cloud.API/Controllers/EmployeeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Cloud.Api.Services;
using Cloud.Api.Models;
using Microsoft.AspNetCore.Mvc;

namespace Cloud.Api.Controllers;

/// <summary>
/// Контроллер для получения сотрудника компании по id
/// </summary>
/// <param name="employeeService">Сервис получения сотрудника компании</param>
/// <param name="logger">Логгер</param>
[ApiController]
[Route("employee")]
public class EmployeesController(
IEmployeeService employeeService,
ILogger<EmployeesController> logger
) : ControllerBase
{
/// <summary>
/// Метод для получения сотрудника компании по id
/// </summary>
/// <param name="id">Идентификатор сотрудника</param>
/// <returns>Информация о сотруднике компании</returns>
/// <response code="200">Успешное получение сотрудника компании</response>
/// <response code="400">Некорректный id сотрудника</response>
[ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
[HttpGet]
public async Task<ActionResult<Employee>> GetEmployee([FromQuery] int id)
{
if (id <= 0)
return BadRequest(new { error = "Id must be a positive number" });

logger.LogInformation("HTTP GET /employee, id: {employeeId}", id);

var employee = await employeeService.GetOrGenerateAsync(id);
return Ok(employee);
}
}
15 changes: 15 additions & 0 deletions Cloud.API/Messaging/IProducerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Cloud.Api.Models;

namespace Cloud.Api.Messaging;

/// <summary>
/// Интерфейс сервиса отправки сгенерированного сотрудника в очередь SQS
/// </summary>
public interface IProducerService
{
/// <summary>
/// Метод отправки сообщения в брокер
/// </summary>
/// <param name="employee">Информация о сотруднике</param>
public Task SendMessage(Employee employee);
}
46 changes: 46 additions & 0 deletions Cloud.API/Messaging/SqsProducerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System.Text.Json;
using Amazon.SQS;
using Amazon.SQS.Model;
using Cloud.Api.Models;

namespace Cloud.Api.Messaging;

/// <summary>
/// Сервис отправки сгенерированного сотрудника в очередь SQS
/// </summary>
/// <param name="sqsClient">Клиент SQS</param>
/// <param name="configuration">Конфигурация приложения</param>
/// <param name="logger">Логгер</param>
public class SqsProducerService(
IAmazonSQS sqsClient,
IConfiguration configuration,
ILogger<SqsProducerService> logger
) : IProducerService
{
private readonly string _queueUrl = configuration["AWS:Resources:SQSQueueUrl"]
?? throw new KeyNotFoundException("SQS queue URL not found in configuration.");

private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);

/// <inheritdoc />
public async Task SendMessage(Employee employee)
{
var json = JsonSerializer.Serialize(employee, _jsonOptions);
var request = new SendMessageRequest
{
QueueUrl = _queueUrl,
MessageBody = json
};

try
{
var response = await sqsClient.SendMessageAsync(request);
logger.LogInformation("Sent message for Employee {Id}, MessageId {MessageId}", employee.Id, response.MessageId);
}
catch (Exception ex)
{
logger.LogError(ex, "Error sending message for Employee {Id}", employee.Id);
throw;
}
}
}
Loading