diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f118..9fad271 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №1 "Кэширование"
+ Вариант №10 "Учебный Курс"
+ Выполнена Марининым Андреем 6511
+ Ссылка на форк
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab..02d06f5 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
+ "BaseAddress": "https://localhost:7125/study-course"
}
diff --git a/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj
new file mode 100644
index 0000000..480c2f4
--- /dev/null
+++ b/CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj
@@ -0,0 +1,24 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ true
+ f765995e-9d3a-45b8-96dc-a5dc50cd0089
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CloudDevelopment.AppHost/Program.cs b/CloudDevelopment.AppHost/Program.cs
new file mode 100644
index 0000000..f3cd8fc
--- /dev/null
+++ b/CloudDevelopment.AppHost/Program.cs
@@ -0,0 +1,13 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var cache = builder.AddRedis("course-cache")
+ .WithRedisInsight(containerName: "course-insight");
+
+var service = builder.AddProject("service-api")
+ .WithReference(cache, "RedisCache")
+ .WaitFor(cache);
+
+builder.AddProject("client")
+ .WaitFor(service);
+
+builder.Build().Run();
diff --git a/CloudDevelopment.AppHost/Properties/launchSettings.json b/CloudDevelopment.AppHost/Properties/launchSettings.json
new file mode 100644
index 0000000..0f3fea2
--- /dev/null
+++ b/CloudDevelopment.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:17010;http://localhost:15047",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21117",
+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22258"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15047",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19001",
+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20248"
+ }
+ }
+ }
+}
diff --git a/CloudDevelopment.AppHost/appsettings.Development.json b/CloudDevelopment.AppHost/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CloudDevelopment.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CloudDevelopment.AppHost/appsettings.json b/CloudDevelopment.AppHost/appsettings.json
new file mode 100644
index 0000000..31c092a
--- /dev/null
+++ b/CloudDevelopment.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj
new file mode 100644
index 0000000..6c036a1
--- /dev/null
+++ b/CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CloudDevelopment.ServiceDefaults/Extensions.cs b/CloudDevelopment.ServiceDefaults/Extensions.cs
new file mode 100644
index 0000000..c7fceef
--- /dev/null
+++ b/CloudDevelopment.ServiceDefaults/Extensions.cs
@@ -0,0 +1,120 @@
+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 Microsoft.Extensions.ServiceDiscovery;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace CloudDevelopment.ServiceDefaults;
+
+// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry.
+// This project should be referenced by each service project in your solution.
+// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults
+public static class Extensions
+{
+ public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.ConfigureOpenTelemetry();
+
+ builder.AddDefaultHealthChecks();
+
+ builder.Services.AddServiceDiscovery();
+
+ builder.Services.ConfigureHttpClientDefaults(http =>
+ {
+ // Turn on resilience by default
+ http.AddStandardResilienceHandler();
+
+ // Turn on service discovery by default
+ http.AddServiceDiscovery();
+ });
+
+ // Uncomment the following to restrict the allowed schemes for service discovery.
+ // builder.Services.Configure(options =>
+ // {
+ // options.AllowedSchemes = ["https"];
+ // });
+
+ return builder;
+ }
+
+ public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.Logging.AddOpenTelemetry(logging =>
+ {
+ logging.IncludeFormattedMessage = true;
+ logging.IncludeScopes = true;
+ });
+
+ builder.Services.AddOpenTelemetry()
+ .WithMetrics(metrics =>
+ {
+ metrics.AddAspNetCoreInstrumentation()
+ .AddHttpClientInstrumentation()
+ .AddRuntimeInstrumentation();
+ })
+ .WithTracing(tracing =>
+ {
+ tracing.AddSource(builder.Environment.ApplicationName)
+ .AddAspNetCoreInstrumentation()
+ // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
+ //.AddGrpcClientInstrumentation()
+ .AddHttpClientInstrumentation();
+ });
+
+ builder.AddOpenTelemetryExporters();
+
+ return builder;
+ }
+
+ private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
+
+ if (useOtlpExporter)
+ {
+ builder.Services.AddOpenTelemetry().UseOtlpExporter();
+ }
+
+ // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
+ //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
+ //{
+ // builder.Services.AddOpenTelemetry()
+ // .UseAzureMonitor();
+ //}
+
+ return builder;
+ }
+
+ public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.Services.AddHealthChecks()
+ // Add a default liveness check to ensure app is responsive
+ .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
+
+ return builder;
+ }
+
+ public static WebApplication MapDefaultEndpoints(this WebApplication app)
+ {
+ // Adding health checks endpoints to applications in non-development environments has security implications.
+ // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
+ if (app.Environment.IsDevelopment())
+ {
+ // All health checks must pass for app to be considered ready to accept traffic after starting
+ app.MapHealthChecks("/health");
+
+ // Only health checks tagged with the "live" tag must pass for app to be considered alive
+ app.MapHealthChecks("/alive", new HealthCheckOptions
+ {
+ Predicate = r => r.Tags.Contains("live")
+ });
+ }
+
+ return app;
+ }
+}
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241..b9c9beb 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -5,6 +5,15 @@ 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}") = "Service.Api", "Service.Api\Service.Api.csproj", "{8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.AppHost", "CloudDevelopment.AppHost\CloudDevelopment.AppHost.csproj", "{B23EF7D0-C8C5-454D-A02C-A20F5076A90B}"
+ ProjectSection(ProjectDependencies) = postProject
+ {AE7EEA74-2FE0-136F-D797-854FD87E022A} = {AE7EEA74-2FE0-136F-D797-854FD87E022A}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.ServiceDefaults", "CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj", "{C7312DF2-3D8D-4908-96B0-2987647254B3}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +24,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
+ {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {8D0E7890-C6A6-4CB1-90E8-1C7672C6171A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B23EF7D0-C8C5-454D-A02C-A20F5076A90B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C7312DF2-3D8D-4908-96B0-2987647254B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C7312DF2-3D8D-4908-96B0-2987647254B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C7312DF2-3D8D-4908-96B0-2987647254B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C7312DF2-3D8D-4908-96B0-2987647254B3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/README.md b/README.md
index dcaa5eb..1d8b03e 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,16 @@
-# Современные технологии разработки программного обеспечения
-[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing)
+Современные технологии разработки программного обеспечения
+Вариант 10 Учебный курс
+Лабораторная работа №1
+1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов
+2. Реализовано:
-## Задание
-### Цель
-Реализация проекта микросервисного бекенда.
+Сущность: Service.Api.Entities.StudyCourse
-### Задачи
-* Реализация межсервисной коммуникации,
-* Изучение работы с брокерами сообщений,
-* Изучение архитектурных паттернов,
-* Изучение работы со средствами оркестрации на примере .NET Aspire,
-* Повторение основ работы с системами контроля версий,
-* Интеграционное тестирование.
+Сервис генерации данных: Service.Api.Generator.StudyCourseGenerator
-### Лабораторные работы
-
-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 диаграмма
-
-
-
-## Варианты заданий
-Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи.
-
-[Список вариантов](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).
+Сервис кэширования: Service.Api.Generator.GeneratorService
+Интерфейс:
+
+
+
diff --git a/Service.Api/Entities/StudyCourse.cs b/Service.Api/Entities/StudyCourse.cs
new file mode 100644
index 0000000..da653ba
--- /dev/null
+++ b/Service.Api/Entities/StudyCourse.cs
@@ -0,0 +1,68 @@
+using System.Text.Json.Serialization;
+namespace Service.Api.Entities;
+
+///
+/// Учебный курс
+///
+public class StudyCourse
+{
+ ///
+ /// Идентификатор курса
+ ///
+ [JsonPropertyName("id")]
+ public int Id { get; set; }
+
+ ///
+ /// Название курса
+ ///
+ [JsonPropertyName("courseName")]
+ public string? CourseName { get; set; }
+
+ ///
+ /// Полное имя преподавателя, ведущего курс
+ ///
+ [JsonPropertyName("teacherFullName")]
+ public string? TeacherFullName { get; set; }
+
+ ///
+ /// Дата начала курса
+ ///
+ [JsonPropertyName("startDate")]
+ public DateOnly? StartDate { get; set; }
+
+ ///
+ /// Дата окончания курса
+ ///
+ [JsonPropertyName("endDate")]
+ public DateOnly? EndDate { get; set; }
+
+ ///
+ /// Максимальное количество студентов, которые могут быть записаны на курс
+ ///
+ [JsonPropertyName("maxStudents")]
+ public int? MaxStudents { get; set; }
+
+ ///
+ /// Текущее количество студентов, записанных на курс
+ ///
+ [JsonPropertyName("currentStudents")]
+ public int? CurrentStudents { get; set; }
+
+ ///
+ /// Указывает, выдается ли сертификат после успешного завершения курса
+ ///
+ [JsonPropertyName("givesCertificate")]
+ public bool? GivesCertificate { get; set; }
+
+ ///
+ /// Стоимость курса.
+ ///
+ [JsonPropertyName("cost")]
+ public decimal? Cost { get; set; }
+
+ ///
+ /// Рейтинг курса от 1 до 5.
+ ///
+ [JsonPropertyName("rating")]
+ public int? Rating { get; set; }
+}
diff --git a/Service.Api/Generator/GeneratorService.cs b/Service.Api/Generator/GeneratorService.cs
new file mode 100644
index 0000000..ebd0954
--- /dev/null
+++ b/Service.Api/Generator/GeneratorService.cs
@@ -0,0 +1,58 @@
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text.Json;
+using System;
+using Service.Api.Entities;
+using Microsoft.Extensions.Configuration;
+
+namespace Service.Api.Generator;
+
+public class GeneratorService(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger) : IGeneratorService
+{
+ private readonly TimeSpan _cacheExpiration = int.TryParse(_configuration["CacheExpiration"], out var seconds)
+ ? TimeSpan.FromSeconds(seconds)
+ : TimeSpan.FromSeconds(3600);
+ public async Task ProcessCourse(int id)
+ {
+ _logger.LogInformation("Processing course with ID: {CourseId}", id);
+ try
+ {
+ _logger.LogInformation("Attempting to retrieve course from cache with ID: {CourseId}", id);
+ var course = await RetrieveFromCache(id);
+ if (course != null)
+ {
+ _logger.LogInformation("Course with ID: {CourseId} retrieved from cache", id);
+ return course;
+ }
+ _logger.LogInformation("Course with ID: {CourseId} not found in cache, generating new course", id);
+ course = StudyCoureGenerator.GenerateCourse(id);
+ _logger.LogInformation("Populating cache with course {id}", id);
+ await PopulateCache(course);
+ return course;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "An error occurred while processing course with ID: {id}", id);
+ throw;
+ }
+ }
+ private async Task RetrieveFromCache(int id)
+ {
+ var json = await _cache.GetStringAsync(id.ToString());
+ if(string.IsNullOrEmpty(json))
+ {
+ _logger.LogInformation("Course with ID: {CourseId} not found in cache", id);
+ return null;
+ }
+ return JsonSerializer.Deserialize(json);
+ }
+ private async Task PopulateCache(StudyCourse course)
+ {
+ var json = JsonSerializer.Serialize(course);
+ var options = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = _cacheExpiration
+ };
+ await _cache.SetStringAsync(course.Id.ToString(), json, options);
+ _logger.LogInformation("Course with ID: {CourseId} stored in cache with expiration of {Expiration}", course.Id, _cacheExpiration);
+ }
+}
\ No newline at end of file
diff --git a/Service.Api/Generator/IGeneratorService.cs b/Service.Api/Generator/IGeneratorService.cs
new file mode 100644
index 0000000..9dd0839
--- /dev/null
+++ b/Service.Api/Generator/IGeneratorService.cs
@@ -0,0 +1,16 @@
+using Service.Api.Entities;
+
+namespace Service.Api.Generator;
+
+///
+/// Интерфейс для запуска юзкейса по обработке учебных курсов
+///
+public interface IGeneratorService
+{
+ ///
+ /// Обработка запроса на генерацию учебного курса.
+ ///
+ /// ИД
+ ///
+ public Task ProcessCourse(int id);
+}
diff --git a/Service.Api/Generator/StudyCoureGenerator.cs b/Service.Api/Generator/StudyCoureGenerator.cs
new file mode 100644
index 0000000..7c3cda6
--- /dev/null
+++ b/Service.Api/Generator/StudyCoureGenerator.cs
@@ -0,0 +1,44 @@
+using Bogus;
+using Service.Api.Entities;
+namespace Service.Api.Generator;
+
+public static class StudyCoureGenerator
+{
+ private static readonly List _firstNames = new(["Donald", "Kanye", "Carl", "Bob", "Alice", "Albert", "Sam", "Andrew"]);
+
+ private static readonly List _secondNames = new(["Smith", "Trump", "Fed", "Stone", "Johnson", "Williams", "Klinton", "Morgan"]);
+
+ private static readonly List _patronymics = new(["Alex", "Bobby", "Steave", "Michael", "John", "Dan", "Ban", "George"]);
+
+ private static readonly List _courseNames = new(["English", "Spanish", "Hand Craft", "Math", "Chinese", "Yoga"]);
+
+ private static readonly int _maxRating = 5;
+ private static readonly int _minRating = 1;
+ private static readonly int _digitsRound = 2;
+ private static readonly int _minCost = 0;
+ private static readonly int _maxCost = 10000000;
+ private static readonly int _minStudents = 0;
+ private static readonly int _maxStudents = 1000;
+ private static DateOnly _minDate = new (2020, 1, 1);
+ private static DateOnly _maxDate = new(2030, 1, 1);
+ private static int _maxYearsForward = 5;
+
+ private static Faker _faker = new Faker("en")
+ .RuleFor(s => s.TeacherFullName, f => $"{f.PickRandom(_firstNames)} {f.PickRandom(_patronymics)} {f.PickRandom(_secondNames)}")
+ .RuleFor(s => s.CourseName, f => f.PickRandom(_courseNames))
+ .RuleFor(s => s.StartDate, f => f.Date.BetweenDateOnly(_minDate, _maxDate))
+ .RuleFor(s => s.EndDate, (f, s) => f.Date.FutureDateOnly(_maxYearsForward, s.StartDate))
+ .RuleFor(s => s.GivesCertificate, f => f.Random.Bool())
+ .RuleFor(s => s.Cost, f => Math.Round(f.Random.Decimal(_minCost, _maxCost), _digitsRound))
+ .RuleFor(s => s.MaxStudents, f => f.Random.Int(_minStudents, _maxStudents))
+ .RuleFor(s => s.CurrentStudents, (f, s) => f.Random.Int(_minStudents, s.MaxStudents ?? _maxStudents))
+ .RuleFor(s => s.Rating, f => f.Random.Int(_minRating, _maxRating));
+
+ public static StudyCourse GenerateCourse(int id)
+ {
+ var course = _faker.Generate();
+ course.Id = id;
+ return course;
+ }
+
+}
diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs
new file mode 100644
index 0000000..9c23b62
--- /dev/null
+++ b/Service.Api/Program.cs
@@ -0,0 +1,20 @@
+using CloudDevelopment.ServiceDefaults;
+using Service.Api.Generator;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("RedisCache");
+builder.Services.AddScoped();
+builder.Services.AddCors(options => options.AddDefaultPolicy(policy =>
+{
+ policy.AllowAnyOrigin();
+ policy.AllowAnyMethod();
+ policy.AllowAnyHeader();
+}));
+var app = builder.Build();
+
+app.MapDefaultEndpoints();
+app.MapGet("/study-course", (IGeneratorService service, int id) => service.ProcessCourse(id));
+app.UseCors();
+app.Run();
diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json
new file mode 100644
index 0000000..192ad86
--- /dev/null
+++ b/Service.Api/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:52805",
+ "sslPort": 44383
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5241",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7125;http://localhost:5241",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj
new file mode 100644
index 0000000..a137604
--- /dev/null
+++ b/Service.Api/Service.Api.csproj
@@ -0,0 +1,18 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/Service.Api/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/Service.Api/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}