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="..\ProjectGenerator\ProjectGenerator.ServiceDefaults\ProjectGenerator.ServiceDefaults.csproj" />
</ItemGroup>

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

namespace Api.Gateway.LoadBalancers;


/// <summary>
/// Балансировщик нагрузки на основе параметра запроса <c>id</c>.
/// </summary>
/// <remarks>
/// Алгоритм: индекс реплики = id % количество_реплик.
/// Это гарантирует, что один и тот же идентификатор всегда попадает
/// на одну и ту же реплику (sticky routing по id).
/// </remarks>
/// <param name="serviceProviderFactory">
/// Делегат, возвращающий список доступных реплик сервиса.
/// Вызывается при каждом запросе, чтобы учитывать динамически
/// изменяющийся пул экземпляров.
/// </param>
public class QueryBasedLoadBalancer(Func<Task<List<Service>>> serviceProviderFactory) : ILoadBalancer
{
public string Type => nameof(QueryBasedLoadBalancer);

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

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

if (!context.Request.Query.TryGetValue("id", out var idValue) ||
!int.TryParse(idValue, out var id) ||
id < 0)
throw new InvalidOperationException("Query parameter 'id' is missing or invalid");

var index = id % services.Count;

return new OkResponse<ServiceHostAndPort>(services[index].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.LoadBalancers;
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<QueryBasedLoadBalancer>((_, _, provider) => new(provider.GetAsync));


var trustedUrls = builder.Configuration.GetSection("CorsOrigins").Get<string[]>() ?? [];
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(trustedUrls)
.WithMethods("GET")
.WithHeaders("Content-Type");
});
});

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:62081",
"sslPort": 44391
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7190;http://localhost:5200",
"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"
}
}
}
13 changes: 13 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"CorsOrigins": [
"http://localhost:5127",
"https://localhost:7282"
]
}
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": "/generate",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/generate",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5000 },
{ "Host": "localhost", "Port": 5001 },
{ "Host": "localhost", "Port": 5002 },
{ "Host": "localhost", "Port": 5003 },
{ "Host": "localhost", "Port": 5004 }
],
"LoadBalancerOptions": {
"Type": "QueryBasedLoadBalancer"
}
}
]
}
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>№2 "Балансировка нагрузки"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№46 "Программный проект"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Митеревым Дмитрием 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To=" https://github.com/Dmiterev/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:7190/generate"
}
30 changes: 30 additions & 0 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ 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}") = "ProjectGenerator.AppHost", "ProjectGenerator\ProjectGenerator.AppHost\ProjectGenerator.AppHost.csproj", "{2BD86B8F-8507-43F0-B17F-9607B7352733}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectGenerator.ServiceDefaults", "ProjectGenerator\ProjectGenerator.ServiceDefaults\ProjectGenerator.ServiceDefaults.csproj", "{8F9985A2-9D06-28F9-3428-8039644EF545}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectGenerator.Api", "ProjectGenerator.Api\ProjectGenerator.Api.csproj", "{AAEE18D8-2A8E-7273-1128-2FA0B1FA40F9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectGenerator.Domain", "ProjectGenerator.Domain\ProjectGenerator.Domain.csproj", "{67E00678-695C-407F-B401-27C9EC3527B1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +25,26 @@ 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
{2BD86B8F-8507-43F0-B17F-9607B7352733}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2BD86B8F-8507-43F0-B17F-9607B7352733}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2BD86B8F-8507-43F0-B17F-9607B7352733}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2BD86B8F-8507-43F0-B17F-9607B7352733}.Release|Any CPU.Build.0 = Release|Any CPU
{8F9985A2-9D06-28F9-3428-8039644EF545}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8F9985A2-9D06-28F9-3428-8039644EF545}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F9985A2-9D06-28F9-3428-8039644EF545}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F9985A2-9D06-28F9-3428-8039644EF545}.Release|Any CPU.Build.0 = Release|Any CPU
{AAEE18D8-2A8E-7273-1128-2FA0B1FA40F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AAEE18D8-2A8E-7273-1128-2FA0B1FA40F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAEE18D8-2A8E-7273-1128-2FA0B1FA40F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAEE18D8-2A8E-7273-1128-2FA0B1FA40F9}.Release|Any CPU.Build.0 = Release|Any CPU
{67E00678-695C-407F-B401-27C9EC3527B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{67E00678-695C-407F-B401-27C9EC3527B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{67E00678-695C-407F-B401-27C9EC3527B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{67E00678-695C-407F-B401-27C9EC3527B1}.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
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
18 changes: 18 additions & 0 deletions ProjectGenerator.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using ProjectGenerator.Api.Services;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.AddRedisDistributedCache("cache");

builder.Services.AddSingleton<ISoftwareProjectGenerator, SoftwareProjectGenerator>();
builder.Services.AddScoped<ISoftwareProjectService, SoftwareProjectService>();

var app = builder.Build();

app.MapDefaultEndpoints();

app.MapGet("/api/generate", async (int id, ISoftwareProjectService service) =>
await service.GetOrGenerate(id));

app.Run();
23 changes: 23 additions & 0 deletions ProjectGenerator.Api/ProjectGenerator.Api.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>
</PropertyGroup>

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

<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.5.2" />
<PackageReference Include="Bogus" Version="35.6.5" />
</ItemGroup>

</Project>
38 changes: 38 additions & 0 deletions ProjectGenerator.Api/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:10098",
"sslPort": 44392
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5283",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7046;http://localhost:5283",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
14 changes: 14 additions & 0 deletions ProjectGenerator.Api/Services/ISoftwareProjectGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using ProjectGenerator.Domain.Models;

namespace ProjectGenerator.Api.Services;

/// <summary>
/// Интерфейс генератора программных проектов
/// </summary>
public interface ISoftwareProjectGenerator
{
/// <summary>
/// Генерирует программный проект с указанным идентификатором
/// </summary>
public SoftwareProject Generate(int id);
}
14 changes: 14 additions & 0 deletions ProjectGenerator.Api/Services/ISoftwareProjectService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using ProjectGenerator.Domain.Models;

namespace ProjectGenerator.Api.Services;

/// <summary>
/// Интерфейс сервиса программных проектов
/// </summary>
public interface ISoftwareProjectService
{
/// <summary>
/// Получает программный проект по идентификатору из кэша или генерирует новый
/// </summary>
public Task<SoftwareProject> GetOrGenerate(int id);
}
Loading