diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..6c6aa3d9 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №6 "Медицинский пациент" + Выполнена Замотохиной Марией 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..88541dd0 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -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": { @@ -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" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..6d94852e 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "http://localhost:5100/medicalpatient-generator" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..01cc81a3 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -3,7 +3,15 @@ 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}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MedicalPatient.AppHost.AppHost", "MedicalPatient.AppHost\MedicalPatient.AppHost.AppHost\MedicalPatient.AppHost.AppHost.csproj", "{892597A3-DF97-470C-AA27-6398D1C68C9E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MedicalPatient.AppHost.ServiceDefaults", "MedicalPatient.AppHost\MedicalPatient.AppHost.ServiceDefaults\MedicalPatient.AppHost.ServiceDefaults.csproj", "{0E685E2F-3762-4FF1-AF4F-A3E204FDF791}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MedicalPatient.Generator", "MedicalPatient.Generator\MedicalPatient.Generator.csproj", "{B9054D03-6CF6-4B8C-8E6F-3D27D39983F5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MedicalPatient.ApiGateway", "MedicalPatient.ApiGateway\MedicalPatient.ApiGateway.csproj", "{30D90454-DACC-4B41-86DF-FD441AC7AB6D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +23,22 @@ 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 + {892597A3-DF97-470C-AA27-6398D1C68C9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {892597A3-DF97-470C-AA27-6398D1C68C9E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {892597A3-DF97-470C-AA27-6398D1C68C9E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {892597A3-DF97-470C-AA27-6398D1C68C9E}.Release|Any CPU.Build.0 = Release|Any CPU + {0E685E2F-3762-4FF1-AF4F-A3E204FDF791}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0E685E2F-3762-4FF1-AF4F-A3E204FDF791}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0E685E2F-3762-4FF1-AF4F-A3E204FDF791}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0E685E2F-3762-4FF1-AF4F-A3E204FDF791}.Release|Any CPU.Build.0 = Release|Any CPU + {B9054D03-6CF6-4B8C-8E6F-3D27D39983F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9054D03-6CF6-4B8C-8E6F-3D27D39983F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9054D03-6CF6-4B8C-8E6F-3D27D39983F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9054D03-6CF6-4B8C-8E6F-3D27D39983F5}.Release|Any CPU.Build.0 = Release|Any CPU + {30D90454-DACC-4B41-86DF-FD441AC7AB6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {30D90454-DACC-4B41-86DF-FD441AC7AB6D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {30D90454-DACC-4B41-86DF-FD441AC7AB6D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {30D90454-DACC-4B41-86DF-FD441AC7AB6D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/MedicalPatient.ApiGateway/Balancer/WeightedRoundRobin.cs b/MedicalPatient.ApiGateway/Balancer/WeightedRoundRobin.cs new file mode 100644 index 00000000..40edc49d --- /dev/null +++ b/MedicalPatient.ApiGateway/Balancer/WeightedRoundRobin.cs @@ -0,0 +1,65 @@ +using Ocelot.LoadBalancer.Errors; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; + +namespace MedicalPatient.ApiGateway.Balancer; + +public class WeightedRoundRobin(IServiceDiscoveryProvider serviceDiscovery, IReadOnlyList? weights = null) + : ILoadBalancer +{ + private readonly int[] _weights = (weights is { Count: > 0 } ? [.. weights] : []); + private int _cursor = -1; + + private List? _wheel; + private int _lastServicesCount = -1; + + public string Type => nameof(WeightedRoundRobin); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var services = await serviceDiscovery.GetAsync(); + + if (services is null) + return new ErrorResponse( + new ServicesAreNullError("Service discovery returned null")); + + if (services.Count == 0) + return new ErrorResponse( + new ServicesAreNullError("No downstream services are available")); + + if (_wheel == null || _lastServicesCount != services.Count) + { + _wheel = BuildWheel(services.Count); + _lastServicesCount = services.Count; + } + + var next = (uint)Interlocked.Increment(ref _cursor); + var wheelIndex = (int)(next % (uint)_wheel.Count); + var serviceIndex = _wheel[wheelIndex]; + + return new OkResponse(services[serviceIndex].HostAndPort); + } + + private List BuildWheel(int servicesCount) + { + var wheel = new List(); + + for (var i = 0; i < servicesCount; i++) + { + var weight = i < _weights.Length ? _weights[i] : 1; + if (weight < 1) weight = 1; + + for (var j = 0; j < weight; j++) + wheel.Add(i); + } + + if (wheel.Count == 0) + wheel.Add(0); + + return wheel; + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/MedicalPatient.ApiGateway/MedicalPatient.ApiGateway.csproj b/MedicalPatient.ApiGateway/MedicalPatient.ApiGateway.csproj new file mode 100644 index 00000000..3a09447f --- /dev/null +++ b/MedicalPatient.ApiGateway/MedicalPatient.ApiGateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/MedicalPatient.ApiGateway/Program.cs b/MedicalPatient.ApiGateway/Program.cs new file mode 100644 index 00000000..ffe8c33b --- /dev/null +++ b/MedicalPatient.ApiGateway/Program.cs @@ -0,0 +1,64 @@ +using MedicalPatient.ApiGateway.Balancer; +using MedicalPatient.AppHost.ServiceDefaults; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +var allowedOrigins = builder.Configuration.GetSection("AllowedOrigins").Get() ?? + ["https://localhost:7282", "http://localhost:5127"]; + +builder.Services.AddCors(options => +{ + options.AddPolicy("ClientCorsPolicy", policy => + { + policy.WithOrigins(allowedOrigins) + .WithMethods("GET", "POST", "PUT", "DELETE") + .WithHeaders("Authorization", "Content-Type") + .AllowCredentials(); + }); +}); + +builder.Configuration + .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +var generators = builder.Configuration.GetSection("Generators").Get() ?? []; + +var configuredWeights = builder.Configuration + .GetSection("Routes:0:DownstreamHostWeights") + .GetChildren() + .Select(x => x.GetValue("Weight", 1)) + .Where(w => w > 0) + .ToArray(); +var weights = configuredWeights.Length > 0 ? configuredWeights : [3, 2, 1]; + +var addressOverrides = new List>(); + +for (var i = 0; i < generators.Length; ++i) +{ + var name = generators[i]; + var url = builder.Configuration[$"services:{name}:http:0"]; + + if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + addressOverrides.Add(new($"Routes:0:DownstreamHostAndPorts:{i}:Host", uri.Host)); + addressOverrides.Add(new($"Routes:0:DownstreamHostAndPorts:{i}:Port", uri.Port.ToString())); + } +} + +if (addressOverrides.Count > 0) + builder.Configuration.AddInMemoryCollection(addressOverrides); + +builder.Services + .AddOcelot(builder.Configuration) + .AddCustomLoadBalancer((route, serviceDiscovery) => + new WeightedRoundRobin(serviceDiscovery, weights)); + +var app = builder.Build(); + +app.UseCors("ClientCorsPolicy"); + +await app.UseOcelot(); +await app.RunAsync(); \ No newline at end of file diff --git a/MedicalPatient.ApiGateway/Properties/launchSettings.json b/MedicalPatient.ApiGateway/Properties/launchSettings.json new file mode 100644 index 00000000..192c4041 --- /dev/null +++ b/MedicalPatient.ApiGateway/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5100", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7293;http://localhost:5100", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/MedicalPatient.ApiGateway/appsettings.Development.json b/MedicalPatient.ApiGateway/appsettings.Development.json new file mode 100644 index 00000000..a3abc347 --- /dev/null +++ b/MedicalPatient.ApiGateway/appsettings.Development.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "GlobalConfiguration": { + "BaseUrl": "http://localhost:5100" + } +} diff --git a/MedicalPatient.ApiGateway/appsettings.json b/MedicalPatient.ApiGateway/appsettings.json new file mode 100644 index 00000000..6e1f905c --- /dev/null +++ b/MedicalPatient.ApiGateway/appsettings.json @@ -0,0 +1,14 @@ +{ + "AllowedOrigins": [ + "https://localhost:7282", + "http://localhost:5127" + ], + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Generators": [ "generator-1", "generator-2", "generator-3" ] +} diff --git a/MedicalPatient.ApiGateway/ocelot.json b/MedicalPatient.ApiGateway/ocelot.json new file mode 100644 index 00000000..078fdc2d --- /dev/null +++ b/MedicalPatient.ApiGateway/ocelot.json @@ -0,0 +1,44 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/medicalpatient-generator", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5101 + }, + { + "Host": "localhost", + "Port": 5102 + }, + { + "Host": "localhost", + "Port": 5103 + } + ], + "UpstreamPathTemplate": "/medicalpatient-generator", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "WeightedRoundRobin" + }, + "DownstreamHostWeights": [ + { + "Host": "localhost", + "Port": 5101, + "Weight": 3 + }, + { + "Host": "localhost", + "Port": 5102, + "Weight": 2 + }, + { + "Host": "localhost", + "Port": 5103, + "Weight": 1 + } + ] + } + ] +} \ No newline at end of file diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/MedicalPatient.AppHost.AppHost.csproj b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/MedicalPatient.AppHost.AppHost.csproj new file mode 100644 index 00000000..a41dea5d --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/MedicalPatient.AppHost.AppHost.csproj @@ -0,0 +1,25 @@ + + + + + Exe + net8.0 + enable + enable + true + fe743bf2-08eb-41c7-817b-f144b739dce3 + + + + + + + + + + + + + + + diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/Program.cs b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/Program.cs new file mode 100644 index 00000000..91e3e18b --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/Program.cs @@ -0,0 +1,39 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var generator1 = builder.AddProject("generator-1") + .WithEndpoint("http", endpoint => endpoint.Port = 5101) + .WithReference(redis) + .WaitFor(redis) + .WithExternalHttpEndpoints(); + +var generator2 = builder.AddProject("generator-2") + .WithEndpoint("http", endpoint => endpoint.Port = 5102) + .WithReference(redis) + .WaitFor(redis) + .WithExternalHttpEndpoints(); + +var generator3 = builder.AddProject("generator-3") + .WithEndpoint("http", endpoint => endpoint.Port = 5103) + .WithReference(redis) + .WaitFor(redis) + .WithExternalHttpEndpoints(); + +var gateway = builder + .AddProject("medicalpatient-apigateway") + .WithReference(generator1) + .WithReference(generator2) + .WithReference(generator3) + .WithExternalHttpEndpoints() + .WaitFor(generator1) + .WaitFor(generator2) + .WaitFor(generator3); + +builder.AddProject("client") + .WithReference(gateway) + .WaitFor(gateway); + +builder.Build().Run(); + diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/Properties/launchSettings.json b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..0358d2e5 --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17189;http://localhost:15186", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21135", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22007" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15186", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19058", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20159" + } + } + } +} diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/appsettings.Development.json b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/appsettings.json b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.ServiceDefaults/Extensions.cs b/MedicalPatient.AppHost/MedicalPatient.AppHost.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..cf67d245 --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.ServiceDefaults/Extensions.cs @@ -0,0 +1,104 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; +using Serilog; + +namespace MedicalPatient.AppHost.ServiceDefaults; + +public static class Extensions +{ + public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) + { + builder.ConfigureSerilog(); + builder.ConfigureOpenTelemetry(); + builder.AddDefaultHealthChecks(); + builder.Services.AddServiceDiscovery(); + builder.Services.ConfigureHttpClientDefaults(http => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + return builder; + } + + public static IHostApplicationBuilder ConfigureSerilog(this IHostApplicationBuilder builder) + { + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(builder.Configuration) + .Enrich.FromLogContext() + .Enrich.WithEnvironmentName() + .Enrich.WithThreadId() + .Enrich.WithMachineName() + .WriteTo.Console(outputTemplate: + "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}") + .CreateLogger(); + + builder.Services.AddSerilog(); + + return builder; + } + + public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder) + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + return builder; + } + + public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder) + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + app.MapHealthChecks("/health"); + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + + return app; + } +} \ No newline at end of file diff --git a/MedicalPatient.AppHost/MedicalPatient.AppHost.ServiceDefaults/MedicalPatient.AppHost.ServiceDefaults.csproj b/MedicalPatient.AppHost/MedicalPatient.AppHost.ServiceDefaults/MedicalPatient.AppHost.ServiceDefaults.csproj new file mode 100644 index 00000000..f0c210f6 --- /dev/null +++ b/MedicalPatient.AppHost/MedicalPatient.AppHost.ServiceDefaults/MedicalPatient.AppHost.ServiceDefaults.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + + + + + diff --git a/MedicalPatient.Generator/MedicalPatient.Generator.csproj b/MedicalPatient.Generator/MedicalPatient.Generator.csproj new file mode 100644 index 00000000..46284771 --- /dev/null +++ b/MedicalPatient.Generator/MedicalPatient.Generator.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + diff --git a/MedicalPatient.Generator/Models/MedicalPatient.cs b/MedicalPatient.Generator/Models/MedicalPatient.cs new file mode 100644 index 00000000..dc138910 --- /dev/null +++ b/MedicalPatient.Generator/Models/MedicalPatient.cs @@ -0,0 +1,57 @@ +namespace MedicalPatient.Generator.Models; + +/// +/// Класс, описывающий карточку медицинского пациента +/// +public class MedicalPatientModel +{ + /// + /// Идентификатор пациента в системе + /// + public int Id { get; set; } + + /// + /// ФИО пациента - конкатенация фамилии, имени и отчества через пробел + /// + public required string FullName { get; set; } + + /// + /// Адрес проживания пациента + /// + public required string Address { get; set; } + + /// + /// Дата рождения - не может быть позже текущей + /// + public required DateOnly BirthDate { get; set; } + + /// + /// Рост - округляется до двух знаков после запятой + /// + public required double Height { get; set; } + + /// + /// Вес - округляется до двух знаков после запятой + /// + public required double Weight { get; set; } + + /// + /// Группа крови (на рукаве) - это число от 1 до 4 + /// + public required int BloodType { get; set; } + + /// + /// Резус-фактор + /// + public required bool RhFactor { get; set; } + + /// + /// Дата последнего осмотра - не может быть раньше даты рождения + /// + public required DateOnly LastInspectionDate { get; set; } + + /// + /// Отметка о вакцинации + /// + public required bool VaccinationMark { get; set; } +} diff --git a/MedicalPatient.Generator/Program.cs b/MedicalPatient.Generator/Program.cs new file mode 100644 index 00000000..2a208018 --- /dev/null +++ b/MedicalPatient.Generator/Program.cs @@ -0,0 +1,54 @@ +using MedicalPatient.Generator.Services; +using MedicalPatient.AppHost.ServiceDefaults; +using Serilog; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + + +Log.Logger = new LoggerConfiguration() + .WriteTo.OpenTelemetry() + .WriteTo.Console() + .CreateLogger(); + +var app = builder.Build(); + +app.UseSerilogRequestLogging(); + +app.MapDefaultEndpoints(); + + +app.MapGet("/medicalpatient-generator", async ( + int id, + MedicalPatientService service, + ILogger logger, + CancellationToken cancellationToken) => +{ + logger.LogInformation("A request was received for a company employee with the ID: {Id}", id); + + if (id <= 0) + { + logger.LogWarning("Invalid ID: {Id}", id); + return Results.BadRequest(new { error = "ID must be > 0" }); + } + + try + { + var application = await service.GetByIdAsync(id, cancellationToken); + return Results.Ok(application); + } + catch (Exception ex) + { + logger.LogError(ex, "Error when receiving data about a medical patient with {Id}", id); + return Results.Problem("An error occurred while processing the request"); + } +}) +.WithName("GetMedicalPatient"); + +app.Run(); \ No newline at end of file diff --git a/MedicalPatient.Generator/Properties/launchSettings.json b/MedicalPatient.Generator/Properties/launchSettings.json new file mode 100644 index 00000000..d9b8aded --- /dev/null +++ b/MedicalPatient.Generator/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5067", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7196;http://localhost:5067", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/MedicalPatient.Generator/Services/MedicalPatientGenerator.cs b/MedicalPatient.Generator/Services/MedicalPatientGenerator.cs new file mode 100644 index 00000000..f2df5229 --- /dev/null +++ b/MedicalPatient.Generator/Services/MedicalPatientGenerator.cs @@ -0,0 +1,104 @@ +using Bogus; +using Bogus.DataSets; +using MedicalPatient.Generator.Models; + +namespace MedicalPatient.Generator.Services; + +/// +/// Генератор данных для пациентов медицинской базы данных. +/// +public class MedicalPatientGenerator(ILogger logger) +{ + private readonly Faker _faker = new Faker("ru") + .RuleFor(x => x.FullName, GenerateFullName) + .RuleFor(x => x.Address, f => + $"г. {f.Address.City()}, ул. {f.Address.StreetName()}, д. {f.Address.BuildingNumber()}, кв. {f.Random.Int(1, 150)}" + ) + .RuleFor(x => x.BirthDate, f => f.Date.PastDateOnly(100)) + .RuleFor(x => x.Height, (f, x) => GenerateHeight(f, x.BirthDate)) + .RuleFor(x => x.Weight, (f, x) => GenerateWeight(f, x.Height)) + .RuleFor(m => m.BloodType, f => f.Random.Int(1, 4)) + .RuleFor(m => m.RhFactor, f => f.Random.Bool()) + .RuleFor(m => m.LastInspectionDate, (f, m) => f.Date.BetweenDateOnly(m.BirthDate, DateOnly.FromDateTime(DateTime.Now))) + .RuleFor(m => m.VaccinationMark, f => f.Random.Bool()); + + /// + /// Функия генерации случайного пациента с указанным идентификатором. + /// + /// Идентификатор пациента. + /// Сгенерированный объект с заполненными полями. + public MedicalPatientModel Generate(int id) + { + logger.LogInformation("Starting the generation of a medical patient with an ID: {Id}", id); + var patient = _faker.Generate(); + patient.Id = id; + + return patient; + } + + /// + /// Функция генерации ФИО пациента с учетом гендера + /// + /// Генератор случайных данных + /// Сгенерированное ФИО в виде единой строки + private static string GenerateFullName(Faker faker) + { + var gender = faker.Person.Gender; + var lastName = faker.Name.LastName(gender); + var firstName = faker.Name.FirstName(gender); + var patronymic = faker.Name.FirstName(Name.Gender.Male) + (gender == Name.Gender.Male ? "вич" : "вна"); + + return string.Join(' ', lastName, firstName, patronymic); + } + + /// + /// Соотношение возраст - диапазон роста дл пациента + /// + /// Возраст пациента в годах + /// Минимальный и максимальный рост для данного возраста + private static (double Min, double Max) HeightRangeByAge(double age) + { + return age switch + { + < 1 => (0.35, 0.80), + < 3 => (0.80, 1.00), + < 7 => (1.00, 1.30), + < 13 => (1.30, 1.60), + < 18 => (1.50, 1.90), + _ => (1.50, 2.10) + }; + } + + /// + /// Функция генерации роста пациента на основе его возраста + /// + /// Генератор случайных данных + /// Дата рождения + /// Рост пациента, округленный до 2х знаков после запятой + private static double GenerateHeight(Faker faker, DateOnly birthDate) + { + var today = DateOnly.FromDateTime(DateTime.Now); + var age = today.Year - birthDate.Year; + + if (birthDate > today.AddYears(-age)) + { + age--; + } + + var (minHeight, maxHeight) = HeightRangeByAge(age); + + return Math.Round(faker.Random.Double(minHeight, maxHeight), 2); + } + + /// + /// Функция генерации веса пациента на основе его роса с помощью индекса массы тела + /// + /// Генератор случайных данных + /// Рост + /// Вес пациента, округленный до 2х знаков после запятой + private static double GenerateWeight(Faker faker, double height) + { + var bmi = faker.Random.Double(15, 40); + return Math.Round((bmi * height * height), 2); + } +} diff --git a/MedicalPatient.Generator/Services/MedicalPatientService.cs b/MedicalPatient.Generator/Services/MedicalPatientService.cs new file mode 100644 index 00000000..8a7b4c79 --- /dev/null +++ b/MedicalPatient.Generator/Services/MedicalPatientService.cs @@ -0,0 +1,77 @@ +using MedicalPatient.Generator.Models; +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; + + +namespace MedicalPatient.Generator.Services; + +/// +/// +/// Сервис для работы с медицинскими пациентами
+/// Каждый сгенерированный пациент сохраняется в кэш, если ранее не было пациента с таким ID
+/// В ином случае значение берется из кэша +/// Генератор случайных данных пациента +/// Кэш, хранящий ранее сгенерированных сотрудников +/// Логгер +/// Конфигурация +public class MedicalPatientService( + MedicalPatientGenerator generator, + IDistributedCache cache, + ILogger logger, + IConfiguration config +) +{ + private readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(config.GetSection("CacheSetting").GetValue("CacheExpirationMinutes", 5)); + private const string CacheKeyPrefix = "medical-patient:"; + + /// + /// Функция для генерации или взятия из кэша сотрудника по id + /// + /// Id сотрудника + /// Токен для отмены операции + /// + public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default) + { + if (id <= 0) + throw new ArgumentOutOfRangeException(nameof(id), "Id must be greater than zero."); + + var cacheKey = $"{CacheKeyPrefix}{id}"; + + logger.LogInformation("Requesting data about a patient with an ID: {Id}", id); + + var cachedData = await cache.GetStringAsync(cacheKey, cancellationToken); + + if (!string.IsNullOrEmpty(cachedData)) + { + logger.LogInformation("Medical patient with {Id} found in cache", id); + try + { + var cachedPatient = JsonSerializer.Deserialize(cachedData); + if (cachedPatient != null) return cachedPatient; + } + catch (JsonException ex) + { + logger.LogWarning(ex, "Invalid JSON structure for patient with ID {Id}", id); + } + } + + logger.LogInformation("The medical patient with {Id} was not found in the cache, a new one will be generated", id); + + var patient = generator.Generate(id); + + var serializedData = JsonSerializer.Serialize(patient); + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }; + + await cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); + + logger.LogInformation( + "A medical patient with {Id} is stored in a cache with TTL {CacheExpiration} m.", + id, + _cacheExpiration.TotalMinutes); + + return patient; + } +} diff --git a/MedicalPatient.Generator/appsettings.Development.json b/MedicalPatient.Generator/appsettings.Development.json new file mode 100644 index 00000000..770d3e93 --- /dev/null +++ b/MedicalPatient.Generator/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "DetailedErrors": true, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/MedicalPatient.Generator/appsettings.json b/MedicalPatient.Generator/appsettings.json new file mode 100644 index 00000000..afd4ec73 --- /dev/null +++ b/MedicalPatient.Generator/appsettings.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CacheSetting": { + "CacheExpirationMinutes": 5 + } +} diff --git a/README.md b/README.md index dcaa5eb7..70bc4a97 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,58 @@ # Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) -## Задание -### Цель -Реализация проекта микросервисного бекенда. +### Вариант №6: +- Доменная область: Медицинский пациент +- Балансировка: Weighted Round Robin +- Брокер: SQS +- Хостинг S3: Localstack -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- +## Лабораторная работа №2 - Балансировка нагрузки + В рамках второй лабораторной работы необходимо: * Настроить оркестрацию на запуск нескольких реплик сервиса генерации, * Реализовать апи гейтвей на основе Ocelot, * Имплементировать алгоритм балансировки нагрузки согласно варианту. + +### Реализовано: +- Добавлен API Gateway на основе Ocelot, настроен конфиг файл +- Реализован класс балансироващика WeightedRoundRobin +- бновлены конфиг-файлы проекта для конкретного запуска, проверена работа балансировщика -
-
+### Скриншоты работащего приложения
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
+ + Поднятые контейнеры + -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. + image -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, - -
-
- -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). -* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). -* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). -* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). -* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. - -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud +
Граф связей в проекте:
-Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. + image -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio
-## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. - -[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) -[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) - -## Схема сдачи - -На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). +
+ + Логи запуска генераторов + -Общая схема: -1. Сделать форк данного репозитория -2. Выполнить задание -3. Сделать PR в данный репозиторий -4. Исправить замечания после code review -5. Получить approve + image -## Критерии оценивания + image -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания +
-Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. +
+ + Демонстрация балансировки + -### Шкала оценивания + image -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу + image -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). -Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). + image +
diff --git a/images/1/image-1.png b/images/1/image-1.png new file mode 100644 index 00000000..02fc8881 Binary files /dev/null and b/images/1/image-1.png differ diff --git a/images/1/image-2.png b/images/1/image-2.png new file mode 100644 index 00000000..1e2316b1 Binary files /dev/null and b/images/1/image-2.png differ diff --git a/images/1/image-4.png b/images/1/image-4.png new file mode 100644 index 00000000..7b9cc978 Binary files /dev/null and b/images/1/image-4.png differ diff --git a/images/1/image-5.png b/images/1/image-5.png new file mode 100644 index 00000000..0d90bc13 Binary files /dev/null and b/images/1/image-5.png differ diff --git a/images/1/image-6.png b/images/1/image-6.png new file mode 100644 index 00000000..57ef610e Binary files /dev/null and b/images/1/image-6.png differ diff --git a/images/1/image.png b/images/1/image.png new file mode 100644 index 00000000..acf1477c Binary files /dev/null and b/images/1/image.png differ