diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..a5e08b1 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кеширование" + Вариант №14 "Медицинский пациeнт" + Выполнена Степановым Дмитрием 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea..6ad691a 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,9 +12,9 @@ "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", + "applicationUrl": "http://localhost:5128", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -22,20 +22,20 @@ "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", + "applicationUrl": "https://localhost:7283;http://localhost:5128", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } -} +} \ No newline at end of file diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab..859496f 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" -} + "BaseAddress": "http://localhost:5171/patient" +} \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..b4f3306 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -3,7 +3,13 @@ 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("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PatientApp.Generator", "GeneratorService\PatientApp.Generator.csproj", "{DB627DDE-E411-4B5B-9FE3-15F9A8EC1491}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PatientApp.AppHost", "Patient\Patient.AppHost\PatientApp.AppHost.csproj", "{03605D0F-0E69-461D-9417-32DD06B53E23}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PatientApp.ServiceDefaults", "Patient\Patient.ServiceDefaults\PatientApp.ServiceDefaults.csproj", "{DA24CCA7-7B4A-871C-985C-DBE0FA1F7524}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +21,18 @@ 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 + {DB627DDE-E411-4B5B-9FE3-15F9A8EC1491}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DB627DDE-E411-4B5B-9FE3-15F9A8EC1491}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DB627DDE-E411-4B5B-9FE3-15F9A8EC1491}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DB627DDE-E411-4B5B-9FE3-15F9A8EC1491}.Release|Any CPU.Build.0 = Release|Any CPU + {03605D0F-0E69-461D-9417-32DD06B53E23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {03605D0F-0E69-461D-9417-32DD06B53E23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {03605D0F-0E69-461D-9417-32DD06B53E23}.Release|Any CPU.ActiveCfg = Release|Any CPU + {03605D0F-0E69-461D-9417-32DD06B53E23}.Release|Any CPU.Build.0 = Release|Any CPU + {DA24CCA7-7B4A-871C-985C-DBE0FA1F7524}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DA24CCA7-7B4A-871C-985C-DBE0FA1F7524}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DA24CCA7-7B4A-871C-985C-DBE0FA1F7524}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DA24CCA7-7B4A-871C-985C-DBE0FA1F7524}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/GeneratorService/GeneratorService.http b/GeneratorService/GeneratorService.http new file mode 100644 index 0000000..1625101 --- /dev/null +++ b/GeneratorService/GeneratorService.http @@ -0,0 +1,6 @@ +@GeneratorService_HostAddress = http://localhost:5104 + +GET {{GeneratorService_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/GeneratorService/Models/Patient.cs b/GeneratorService/Models/Patient.cs new file mode 100644 index 0000000..da63ca6 --- /dev/null +++ b/GeneratorService/Models/Patient.cs @@ -0,0 +1,21 @@ +namespace PatientApp.Generator.Models; + +public class Patient +{ + public int Id { get; set; } + public string FullName { get; set; } + public DateOnly Birthday { get; set; } + public string Address { get; set; } + + public double Height { get; set; } + public double Weight { get; set; } + + public int BloodType { get; set; } + + public bool Resus { get; set; } + + public DateOnly LastVisit { get; set; } + + public bool Vactination { get; set; } + +} diff --git a/GeneratorService/PatientApp.Generator.csproj b/GeneratorService/PatientApp.Generator.csproj new file mode 100644 index 0000000..597bcab --- /dev/null +++ b/GeneratorService/PatientApp.Generator.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + diff --git a/GeneratorService/Program.cs b/GeneratorService/Program.cs new file mode 100644 index 0000000..5872725 --- /dev/null +++ b/GeneratorService/Program.cs @@ -0,0 +1,58 @@ +using PatientApp.Generator.Services; +using PatientApp.ServiceDefaults; +using Serilog; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); +}); + +var app = builder.Build(); + +app.UseCors(); +app.UseSerilogRequestLogging(); + +app.MapDefaultEndpoints(); + +app.MapGet("/patient", async ( + int id, + PatientService service, + ILogger logger, + CancellationToken cancellationToken) => +{ + logger.LogInformation($"Received request for patient with ID: {id}"); + + if (id <= 0) + { + logger.LogWarning($"Received invalid ID: {id}"); + return Results.BadRequest(new { error = "ID must be a positive number" }); + } + + try + { + var application = await service.GetByIdAsync(id, cancellationToken); + return Results.Ok(application); + } + catch (Exception ex) + { + logger.LogError(ex, $"Error while getting patient {id}"); + return Results.Problem("An error occurred while processing the request"); + } +}) +.WithName("GetPatient"); + +app.Run(); diff --git a/GeneratorService/Properties/launchSettings.json b/GeneratorService/Properties/launchSettings.json new file mode 100644 index 0000000..ea1476c --- /dev/null +++ b/GeneratorService/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5171", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7171;http://localhost:5171", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/GeneratorService/Services/Generator.cs b/GeneratorService/Services/Generator.cs new file mode 100644 index 0000000..7e0ea0b --- /dev/null +++ b/GeneratorService/Services/Generator.cs @@ -0,0 +1,37 @@ +using Bogus; +using Bogus.DataSets; +using static System.Math; +using PatientApp.Generator.Models; + +namespace PatientApp.Generator.Services; + +public class PatientGenerator(ILogger logger) +{ + private readonly Faker _faker = new Faker("ru") + .RuleFor(x => x.FullName, GeneratePatientFullName) + .RuleFor(x => x.Birthday, f => f.Date.PastDateOnly()) + .RuleFor(x => x.Address, f => f.Address.FullAddress()) + .RuleFor(x => x.Weight, f => Round(f.Random.Double(5, 120), 2)) + .RuleFor(x => x.Height, f => Round(f.Random.Double(50, 200), 2)) + .RuleFor(x => x.BloodType, f => f.Random.Int(1, 4)) + .RuleFor(x => x.Resus, f => f.Random.Bool()) + .RuleFor(x => x.Vactination, f => f.Random.Bool()) + .RuleFor(x => x.LastVisit, (f, patient) => f.Date.BetweenDateOnly(patient.Birthday, DateOnly.FromDateTime(DateTime.UtcNow)) + ); + + public Patient Generate(int id) + { + logger.LogInformation($"Generating Patient with ID: {id}"); + return _faker.UseSeed(id).RuleFor(x => x.Id, _ => id).Generate(); + } + + private static string GeneratePatientFullName(Faker faker) + { + var gender = faker.Person.Gender; + var firstName = faker.Name.FirstName(gender); + var lastName = faker.Name.LastName(gender); + var patronymic = faker.Name.FirstName(Name.Gender.Male) + (gender == Name.Gender.Male ? "еевич" : "еевна"); + + return string.Join(' ', firstName, lastName, patronymic); + } +} \ No newline at end of file diff --git a/GeneratorService/Services/PatientService.cs b/GeneratorService/Services/PatientService.cs new file mode 100644 index 0000000..94f1b8d --- /dev/null +++ b/GeneratorService/Services/PatientService.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; +using PatientApp.Generator.Services; +using PatientApp.Generator.Models; + +public class PatientService( + PatientGenerator generator, + IDistributedCache cache, + ILogger logger, + IConfiguration config +) +{ + private readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(config.GetSection("CacheSetting").GetValue("CacheExpirationMinutes", 5)); + private const string CacheKeyPrefix = "patient:"; + + public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"{CacheKeyPrefix}{id}"; + + logger.LogInformation($"Patient with Id: {id} was requested"); + + var cachedData = await cache.GetStringAsync(cacheKey, cancellationToken); + + if (!string.IsNullOrEmpty(cachedData)) + { + logger.LogInformation($"Patient with {id} was found in cache"); + var cachedPatient = JsonSerializer.Deserialize(cachedData); + if (cachedPatient != null) return cachedPatient; + } + + logger.LogInformation($"Patient with {id} was found in cache, start generating"); + + 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($"Patint with Id: {id} was saved to cache with TTL {_cacheExpiration.TotalMinutes} minutes"); + + return patient; + } +} \ No newline at end of file diff --git a/GeneratorService/appsettings.Development.json b/GeneratorService/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/GeneratorService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/GeneratorService/appsettings.json b/GeneratorService/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/GeneratorService/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Patient/Patient.AppHost/AppHost.cs b/Patient/Patient.AppHost/AppHost.cs new file mode 100644 index 0000000..63ea5ec --- /dev/null +++ b/Patient/Patient.AppHost/AppHost.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var generator = builder.AddProject("generator") + .WithReference(redis) + .WithExternalHttpEndpoints(); + +builder.AddProject("client") + .WithReference(generator); + +builder.Build().Run(); diff --git a/Patient/Patient.AppHost/PatientApp.AppHost.csproj b/Patient/Patient.AppHost/PatientApp.AppHost.csproj new file mode 100644 index 0000000..17e5a12 --- /dev/null +++ b/Patient/Patient.AppHost/PatientApp.AppHost.csproj @@ -0,0 +1,25 @@ + + + + + + Exe + net8.0 + enable + enable + 9850a275-b1ed-4763-b4e3-9c0fbc45d25f + + + + + + + + + + + + + + + diff --git a/Patient/Patient.AppHost/Properties/launchSettings.json b/Patient/Patient.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..f1080df --- /dev/null +++ b/Patient/Patient.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17170;http://localhost:15170", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21170", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22170" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15170", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19170", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20170" + } + } + } +} diff --git a/Patient/Patient.AppHost/appsettings.Development.json b/Patient/Patient.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Patient/Patient.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Patient/Patient.AppHost/appsettings.json b/Patient/Patient.AppHost/appsettings.json new file mode 100644 index 0000000..888f884 --- /dev/null +++ b/Patient/Patient.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} \ No newline at end of file diff --git a/Patient/Patient.ServiceDefaults/Extensions.cs b/Patient/Patient.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..89d28b6 --- /dev/null +++ b/Patient/Patient.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 PatientApp.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/Patient/Patient.ServiceDefaults/PatientApp.ServiceDefaults.csproj b/Patient/Patient.ServiceDefaults/PatientApp.ServiceDefaults.csproj new file mode 100644 index 0000000..7d10514 --- /dev/null +++ b/Patient/Patient.ServiceDefaults/PatientApp.ServiceDefaults.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index dcaa5eb..03ec443 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,65 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) - -## Задание -### Цель -Реализация проекта микросервисного бекенда. - -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. - -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. - -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
- -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. - -
-
-
-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, чтобы они попали на ревью нужному преподавателю. - -По итогу работы в семестре должна получиться следующая информационная система: -
-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 - -## Критерии оценивания - -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания - -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. - -### Шкала оценивания - -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу - -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](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). - +# Cloud Development (вариант 14 «Медицинский пациент») + +> Студент: Дмитрий Степанов, группа 6511. + +## Описание + +- **GeneratorService** — минималистичный ASP.NET Core API, который генерирует карточку пациента по идентификатору, кеширует результат в Redis и отдает его клиенту. +- **Patient** — папка с оркестратором .NET Aspire AppHost. + +## REST API + +### `GET /patient?id={int}` + +| Параметр | Тип | Обязателен | Описание | +|----------|-----|------------|----------| +| `id` | int (>0) | да | Одновременно идентификатор пациента и seed для генератора; проверяется на положительность. | + +Ответ `200 OK` содержит JSON‑объект с полями: + +| Поле | Тип | Пример | Описание | +|---------------|----------|--------------------------------|----------------------------------------| +| `id` | int | `42` | Первичный ключ записи. | +| `fullName` | string | `«Ирина Смирнова Сергеевна»` | ФИО пациента на русском языке. | +| `birthday` | DateOnly | `1993-07-20` | Дата рождения. | +| `address` | string | `«г. Самара, ул. Карла Маркса...»` | Полный адрес. | +| `height` | double | `167.35` | Рост в сантиметрах. | +| `weight` | double | `61.12` | Вес в килограммах. | +| `bloodType` | int | `2` | Группа крови (1–4). | +| `resus` | bool | `true` | Фактор резус. | +| `lastVisit` | DateOnly | `2026-02-17` | Дата последнего визита. | +| `vactination` | bool | `false` | Наличие прививки. | + +Возможные статусы: + +- `200 OK` — данные найдены (из кеша или заново сгенерированы). +- `400 BadRequest` — `id <= 0`. +- `500 Internal Server Error` — непредвиденная ошибка (возвращается `ProblemDetails`). + +Повторный вызов с тем же `id` в течение TTL вернет данные быстрее и будет сопровождаться логом «Patient ... was found in cache». + +## Структура репозитория + +``` +cloud-development/ +├─ Client.Wasm/ +│ ├─ Components/ +│ ├─ Layout/ +│ ├─ Pages/Home.razor +│ └─ wwwroot/appsettings.json # Конфигурация клиента +├─ GeneratorService/ +│ ├─ Models/Patient.cs # Объектная модель +│ ├─ Services/{Generator,PatientService}.cs # Сервис генерации и генератор +│ └─ Program.cs +├─ Patient/ +│ ├─ Patient.AppHost/ +│ └─ Patient.ServiceDefaults/ +├─ .github/workflows/setup_pr.yml +├─ CloudDevelopment.sln +└─ LICENSE +``` + +## Скрины работы +![Сервисы](image.png) +![Ответ клиента](image-1.png) +![Трассировка](image-2.png) \ No newline at end of file diff --git a/image-1.png b/image-1.png new file mode 100644 index 0000000..9c57cca Binary files /dev/null and b/image-1.png differ diff --git a/image-2.png b/image-2.png new file mode 100644 index 0000000..1526fc6 Binary files /dev/null and b/image-2.png differ diff --git a/image.png b/image.png new file mode 100644 index 0000000..5f22ea2 Binary files /dev/null and b/image.png differ