Skip to content
Open
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 ApiGateway/ApiGateway.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="23.4.2" />
</ItemGroup>

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

</Project>
6 changes: 6 additions & 0 deletions ApiGateway/LoadBalancing/ServicesAreEmptyError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
using Ocelot.Errors;

namespace ApiGateway.LoadBalancing;

public sealed class ServicesAreEmptyError(string message)
: Error(message, OcelotErrorCode.UnableToFindDownstreamRouteError, 503);
48 changes: 48 additions & 0 deletions ApiGateway/LoadBalancing/WeightedRoundRobinBalancer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Responses;
using Ocelot.Values;

namespace ApiGateway.LoadBalancing;

/// <summary>
/// Взвешенная карусель (Weighted Round Robin).
/// Каждой реплике присваивается вес — она обслуживает ровно weight запросов подряд,
/// после чего очередь переходит к следующей реплике.
/// Веса: R1=3, R2=2, R3=1 → R1,R1,R1,R2,R2,R3,R1,...
/// </summary>
public sealed class WeightedRoundRobinBalancer(Func<Task<List<Service>>> services) : ILoadBalancer
{
private readonly Func<Task<List<Service>>> _services = services;
private readonly int[] _weights = [3, 2, 1];
private readonly object _lock = new();

private int _currentIndex = -1;
private int _remainingCalls = 0;

public string Type => nameof(WeightedRoundRobinBalancer);

public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext)
{
var available = await _services.Invoke();

if (available is null || available.Count == 0)
return new ErrorResponse<ServiceHostAndPort>(
new ServicesAreEmptyError("No downstream services available"));

lock (_lock)
{
if (_currentIndex == -1 || _remainingCalls == 0)
{
_currentIndex = (_currentIndex + 1) % available.Count;
_remainingCalls = _weights[_currentIndex % _weights.Length];
}

var service = available[_currentIndex];
_remainingCalls--;

return new OkResponse<ServiceHostAndPort>(service.HostAndPort);
}
}

public void Release(ServiceHostAndPort hostAndPort) { }
}
25 changes: 25 additions & 0 deletions ApiGateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using ApiGateway.LoadBalancing;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot()
.AddCustomLoadBalancer<WeightedRoundRobinBalancer>((_, _, provider) => new(provider.GetAsync));

builder.Services.AddCors(options => options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin();
policy.WithMethods("GET");
policy.WithHeaders("Content-Type");
}));

var app = builder.Build();

app.UseCors();

await app.UseOcelot();

app.Run();
12 changes: 12 additions & 0 deletions ApiGateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"profiles": {
"ApiGateway": {
"commandName": "Project",
"launchBrowser": false,
"applicationUrl": "http://localhost:5200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
9 changes: 9 additions & 0 deletions ApiGateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
18 changes: 18 additions & 0 deletions ApiGateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/patient",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/patient",
"DownstreamScheme": "http",
"LoadBalancerOptions": {
"Type": "WeightedRoundRobinBalancer"
},
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 15000 },
{ "Host": "localhost", "Port": 15001 },
{ "Host": "localhost", "Port": 15002 }
]
}
]
}
24 changes: 24 additions & 0 deletions AppHost/AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<Sdk Name="Aspire.AppHost.Sdk" Version="9.5.2" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsAspireHost>true</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.2" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.5.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\GeneratorService\GeneratorService.csproj" />
<ProjectReference Include="..\ApiGateway\ApiGateway.csproj" />
<ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" />
<ProjectReference Include="..\ServiceDefaults\ServiceDefaults.csproj" />
</ItemGroup>

</Project>
20 changes: 20 additions & 0 deletions AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var builder = DistributedApplication.CreateBuilder(args);

var redis = builder.AddRedis("redis")
.WithRedisInsight();

var client = builder.AddProject<Projects.Client_Wasm>("client");

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

for (var i = 0; i < 3; i++)
{
var replica = builder.AddProject<Projects.GeneratorService>($"generator-service-{i}", launchProfileName: null)
.WithHttpEndpoint(port: 15000 + i)
.WithReference(redis)
.WaitFor(redis)
.WithEnvironment("Cors__AllowedOrigin", client.GetEndpoint("http"));
gateway.WaitFor(replica);
}

builder.Build().Run();
16 changes: 16 additions & 0 deletions AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"profiles": {
"AppHost": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17193;http://localhost:15237",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21193",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22057"
}
}
}
}
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>№ 1</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№ 18</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Чумаковым Иваном 6511</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/mestromezer/cloud-development/tree/main/">Ссылка на форк</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
9 changes: 1 addition & 8 deletions Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BaseAddress": ""
"BaseAddress": "http://localhost:5200/patient"
}
32 changes: 31 additions & 1 deletion CloudDevelopment.sln
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
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}") = "AppHost", "AppHost\AppHost.csproj", "{B1C2D3E4-F5A6-7890-ABCD-EF1234567890}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneratorService", "GeneratorService\GeneratorService.csproj", "{139BD442-54A6-9109-CF9A-53DA218D46F2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneratorService.Tests", "GeneratorService.Tests\GeneratorService.Tests.csproj", "{EBCA1829-1CB1-773B-8241-CE00EBFBCF9C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceDefaults", "ServiceDefaults\ServiceDefaults.csproj", "{9F0B1437-6E39-4706-8A9D-89BCE4B31AA0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiGateway", "ApiGateway\ApiGateway.csproj", "{C2D3E4F5-A6B7-8901-CDEF-234567890ABC}"
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
{B1C2D3E4-F5A6-7890-ABCD-EF1234567890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B1C2D3E4-F5A6-7890-ABCD-EF1234567890}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B1C2D3E4-F5A6-7890-ABCD-EF1234567890}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B1C2D3E4-F5A6-7890-ABCD-EF1234567890}.Release|Any CPU.Build.0 = Release|Any CPU
{139BD442-54A6-9109-CF9A-53DA218D46F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{139BD442-54A6-9109-CF9A-53DA218D46F2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{139BD442-54A6-9109-CF9A-53DA218D46F2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{139BD442-54A6-9109-CF9A-53DA218D46F2}.Release|Any CPU.Build.0 = Release|Any CPU
{EBCA1829-1CB1-773B-8241-CE00EBFBCF9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EBCA1829-1CB1-773B-8241-CE00EBFBCF9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EBCA1829-1CB1-773B-8241-CE00EBFBCF9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EBCA1829-1CB1-773B-8241-CE00EBFBCF9C}.Release|Any CPU.Build.0 = Release|Any CPU
{9F0B1437-6E39-4706-8A9D-89BCE4B31AA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9F0B1437-6E39-4706-8A9D-89BCE4B31AA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9F0B1437-6E39-4706-8A9D-89BCE4B31AA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9F0B1437-6E39-4706-8A9D-89BCE4B31AA0}.Release|Any CPU.Build.0 = Release|Any CPU
{C2D3E4F5-A6B7-8901-CDEF-234567890ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C2D3E4F5-A6B7-8901-CDEF-234567890ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2D3E4F5-A6B7-8901-CDEF-234567890ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2D3E4F5-A6B7-8901-CDEF-234567890ABC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
23 changes: 23 additions & 0 deletions GeneratorService.Tests/GeneratorService.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\GeneratorService\GeneratorService.csproj" />
</ItemGroup>

</Project>
62 changes: 62 additions & 0 deletions GeneratorService.Tests/MedicalPatientGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using GeneratorService.Generators;
using Xunit;

namespace GeneratorService.Tests;

public sealed class MedicalPatientGeneratorTests
{
public static readonly DateOnly Today = DateOnly.FromDateTime(DateTime.Today);

public static IEnumerable<object[]> Patients() =>
Enumerable.Range(1, 300).Select(i => new object[] { MedicalPatientGenerator.Generate(i) });

[Theory]
[MemberData(nameof(Patients))]
public void Id_MatchesRequested(GeneratorService.Models.MedicalPatient p)
=> Assert.True(p.Id > 0);

[Theory]
[MemberData(nameof(Patients))]
public void FullName_HasThreeParts(GeneratorService.Models.MedicalPatient p)
=> Assert.Equal(3, p.FullName.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);

[Theory]
[MemberData(nameof(Patients))]
public void BirthDate_NotInFuture(GeneratorService.Models.MedicalPatient p)
=> Assert.True(p.BirthDate <= Today);

[Theory]
[MemberData(nameof(Patients))]
public void Height_InReasonableBounds(GeneratorService.Models.MedicalPatient p)
=> Assert.InRange(p.Height, 50.0, 220.0);

[Theory]
[MemberData(nameof(Patients))]
public void Height_RoundedToTwoDecimals(GeneratorService.Models.MedicalPatient p)
=> Assert.Equal(p.Height, Math.Round(p.Height, 2));

[Theory]
[MemberData(nameof(Patients))]
public void Weight_InReasonableBounds(GeneratorService.Models.MedicalPatient p)
=> Assert.InRange(p.Weight, 2.5, 200.0);

[Theory]
[MemberData(nameof(Patients))]
public void Weight_RoundedToTwoDecimals(GeneratorService.Models.MedicalPatient p)
=> Assert.Equal(p.Weight, Math.Round(p.Weight, 2));

[Theory]
[MemberData(nameof(Patients))]
public void BloodGroup_Between1And4(GeneratorService.Models.MedicalPatient p)
=> Assert.InRange(p.BloodGroup, 1, 4);

[Theory]
[MemberData(nameof(Patients))]
public void LastExamination_NotBeforeBirthDate(GeneratorService.Models.MedicalPatient p)
=> Assert.True(p.LastExaminationDate >= p.BirthDate);

[Theory]
[MemberData(nameof(Patients))]
public void LastExamination_NotInFuture(GeneratorService.Models.MedicalPatient p)
=> Assert.True(p.LastExaminationDate <= Today);
}
Loading
Loading