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>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

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

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

</Project>
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;
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((sp, _, provider) =>
new WeightedRoundRobin(provider.GetAsync, sp.GetRequiredService<IConfiguration>()));

var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];

builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(allowedOrigins)
.AllowAnyHeader()
.WithMethods("GET");
});
});

var app = builder.Build();

app.UseCors();

app.MapDefaultEndpoints();

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:6371",
"sslPort": 44374
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5116",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7145;http://localhost:5116",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
56 changes: 56 additions & 0 deletions Api.Gateway/WeightedRoundRobin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway;

/// <summary>
/// Балансировщик нагрузки «Взвешенная карусель» (Weighted Round Robin).
/// Реплики перебираются циклически; каждая обрабатывает ровно <c>W</c> запросов подряд,
/// где <c>W</c> — её вес из секции <c>LoadBalancer:Weights</c> в конфигурации (0-based).
/// </summary>
/// <param name="services">Делегат для получения списка доступных реплик сервиса.</param>
/// <param name="configuration">Конфигурация приложения с секцией <c>LoadBalancer:Weights</c>.</param>
public class WeightedRoundRobin(
Func<Task<List<Service>>> services,
IConfiguration configuration) : ILoadBalancer
{
public string Type => nameof(WeightedRoundRobin);

private readonly int[] _weights = configuration.GetSection("LoadBalancer:Weights").Get<int[]>() ?? [];
private readonly object _lock = new();
private int _index;
private int _used;

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

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

lock (_lock)
{
if (_index >= pool.Count)
{
_index = 0;
_used = 0;
}

if (_used >= Weight(_index))
{
_index = (_index + 1) % pool.Count;
_used = 0;
}

_used++;
return new OkResponse<ServiceHostAndPort>(pool[_index].HostAndPort);
}
}

public void Release(ServiceHostAndPort hostAndPort) { }

/// <summary>Возвращает вес реплики по индексу. Если не задан или не положителен — возвращает 1.</summary>
/// <param name="i">Индекс реплики.</param>
private int Weight(int i) => i < _weights.Length && _weights[i] > 0 ? _weights[i] : 1;
}
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"
}
}
}
18 changes: 18 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Cors": {
"AllowedOrigins": [
"http://localhost:5127",
"https://localhost:7282"
]
},
"LoadBalancer": {
"Weights": [ 3, 2, 1, 1, 1 ]
}
}
20 changes: 20 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/vehicle",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/vehicle",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 8000 },
{ "Host": "localhost", "Port": 8001 },
{ "Host": "localhost", "Port": 8002 },
{ "Host": "localhost", "Port": 8003 },
{ "Host": "localhost", "Port": 8004 }
],
"LoadBalancerOptions": {
"Type": "WeightedRoundRobin"
}
}
]
}
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>№27 "Транспортное средство"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнила <Strong>Лаврук Маргарита 6512</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/Mlavrukk/cloud-development">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
6 changes: 3 additions & 3 deletions Client.Wasm/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:5127",
"environmentVariables": {
Expand All @@ -22,7 +22,7 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "https://localhost:7282;http://localhost:5127",
"environmentVariables": {
Expand All @@ -31,7 +31,7 @@
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
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:7145/vehicle"
}
36 changes: 36 additions & 0 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ VisualStudioVersion = 17.14.36811.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.AppHost", "VehicleVault\VehicleVault.AppHost\VehicleVault.AppHost.csproj", "{675E2979-6231-45C9-A79D-E8D1BE095D7E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.ServiceDefaults", "VehicleVault\VehicleVault.ServiceDefaults\VehicleVault.ServiceDefaults.csproj", "{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.Api", "VehicleVault.Api\VehicleVault.Api.csproj", "{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.AppHost.Tests", "VehicleVault\VehicleVault.AppHost.Tests\VehicleVault.AppHost.Tests.csproj", "{F1B6E908-BF85-4F6D-87B9-67F2D3345D57}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "File.Service", "File.Service\File.Service.csproj", "{DF944664-05C9-E01F-B262-C8B381C1EFE1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +27,30 @@ Global
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Release|Any CPU.Build.0 = Release|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Release|Any CPU.Build.0 = Release|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Release|Any CPU.Build.0 = Release|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU
{F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F1B6E908-BF85-4F6D-87B9-67F2D3345D57}.Release|Any CPU.Build.0 = Release|Any CPU
{DF944664-05C9-E01F-B262-C8B381C1EFE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DF944664-05C9-E01F-B262-C8B381C1EFE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DF944664-05C9-E01F-B262-C8B381C1EFE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DF944664-05C9-E01F-B262-C8B381C1EFE1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
44 changes: 44 additions & 0 deletions File.Service/Controllers/VehicleFilesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using File.Service.Storage;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Nodes;

namespace File.Service.Controllers;

/// <summary>
/// Контроллер для получения сохранённых в S3 файлов транспортных средств
/// </summary>
/// <param name="storage">Сервис S3-хранилища</param>
/// <param name="logger">Логгер</param>
[ApiController]
[Route("api/files")]
public class VehicleFilesController(
IVehicleStorageService storage,
ILogger<VehicleFilesController> logger) : ControllerBase
{
/// <summary>
/// Возвращает список ключей файлов в бакете
/// </summary>
[HttpGet]
public async Task<ActionResult<List<string>>> List()
{
var keys = await storage.ListKeys();
return Ok(keys);
}

/// <summary>
/// Возвращает JSON-файл транспортного средства по идентификатору
/// </summary>
/// <param name="id">Идентификатор транспортного средства</param>
/// <returns>JSON транспортного средства; 404, если файл отсутствует</returns>
[HttpGet("{id:int}")]
public async Task<ActionResult<JsonNode>> Get(int id)
{
var node = await storage.Download(IVehicleStorageService.KeyFor(id));
if (node is null)
{
logger.LogInformation("Vehicle {Id} not found in storage", id);
return NotFound();
}
return Ok(node);
}
}
23 changes: 23 additions & 0 deletions File.Service/File.Service.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

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

<ItemGroup>
<PackageReference Include="AWSSDK.S3" Version="4.0.18.7" />
<PackageReference Include="AWSSDK.SQS" Version="4.0.2.15" />
<PackageReference Include="LocalStack.Client" Version="2.0.0" />
<PackageReference Include="LocalStack.Client.Extensions" Version="2.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.4" />
</ItemGroup>

</Project>
Loading
Loading