diff --git a/Client.Wasm/Client.Wasm.csproj b/Client.Wasm/Client.Wasm.csproj index 0ba9f90..1c371bf 100644 --- a/Client.Wasm/Client.Wasm.csproj +++ b/Client.Wasm/Client.Wasm.csproj @@ -10,6 +10,10 @@ + + + + diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..1115345 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер № 2 + Вариант № 52 + Выполнена Томашайтисом Павлом 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 4dda7c0..d319d30 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7170/land-plot" + "BaseAddress": "https://localhost:5000/course-management" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln deleted file mode 100644 index cb48241..0000000 --- a/CloudDevelopment.sln +++ /dev/null @@ -1,25 +0,0 @@ - -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 -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {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 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} - EndGlobalSection -EndGlobal diff --git a/CourseManagement.ApiGateway/CourseManagement.ApiGateway.csproj b/CourseManagement.ApiGateway/CourseManagement.ApiGateway.csproj new file mode 100644 index 0000000..d5b5b8d --- /dev/null +++ b/CourseManagement.ApiGateway/CourseManagement.ApiGateway.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + diff --git a/CourseManagement.ApiGateway/LoadBalancers/QueryBased.cs b/CourseManagement.ApiGateway/LoadBalancers/QueryBased.cs new file mode 100644 index 0000000..3fb1a70 --- /dev/null +++ b/CourseManagement.ApiGateway/LoadBalancers/QueryBased.cs @@ -0,0 +1,44 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace CourseManagement.ApiGateway.LoadBalancers; + +/// +/// Балансировщик нагрузки на основе запроса +/// +/// Логгер +/// Список сервисов +public class QueryBased(ILogger logger, List services) : ILoadBalancer +{ + /// + /// Тип балансировщика нагрузки + /// + public string Type => "QueryBased"; + + /// + /// Метод выбора сервиса на основе запроса + /// + /// HTTP запрос + /// Выбранный сервис + public Task> LeaseAsync(HttpContext httpContext) + { + var idString = httpContext.Request.Query["id"].FirstOrDefault(); + + if (!int.TryParse(idString, out var id)) + id = 0; + + var service = services[id % services.Count]; + + logger.LogInformation("Request {ResourceId} sent to service on port {servicePort}", id, service.HostAndPort.DownstreamPort); + + return Task.FromResult>( + new OkResponse(service.HostAndPort)); + } + + /// + /// Метод очистки ресурсов для сервиса + /// + /// Параметры сервиса + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/CourseManagement.ApiGateway/Program.cs b/CourseManagement.ApiGateway/Program.cs new file mode 100644 index 0000000..ae37569 --- /dev/null +++ b/CourseManagement.ApiGateway/Program.cs @@ -0,0 +1,40 @@ +using CourseManagement.ApiGateway.LoadBalancers; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +// Подключение конфига Ocelot +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); + +// Добавление Ocelot с Query Based балансировщиком нагрузки +builder.Services.AddOcelot() + .AddCustomLoadBalancer((serviceProvider, downstreamRoute, serviceDiscoveryProvider) => + { + var logger = serviceProvider.GetRequiredService>(); + + var services = serviceDiscoveryProvider.GetAsync().GetAwaiter().GetResult().ToList(); + + return new QueryBased(logger, services); + }); + +// CORS +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowClient", policy => + { + policy.AllowAnyOrigin() + .WithMethods("GET") + .WithHeaders("Content-Type"); + }); +}); + +var app = builder.Build(); + +app.UseCors("AllowClient"); + +await app.UseOcelot(); + +app.Run(); \ No newline at end of file diff --git a/CourseManagement.ApiGateway/Properties/launchSettings.json b/CourseManagement.ApiGateway/Properties/launchSettings.json new file mode 100644 index 0000000..48bc659 --- /dev/null +++ b/CourseManagement.ApiGateway/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5256", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7253;http://localhost:5256", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CourseManagement.ApiGateway/appsettings.Development.json b/CourseManagement.ApiGateway/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CourseManagement.ApiGateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseManagement.ApiGateway/appsettings.json b/CourseManagement.ApiGateway/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/CourseManagement.ApiGateway/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CourseManagement.ApiGateway/ocelot.json b/CourseManagement.ApiGateway/ocelot.json new file mode 100644 index 0000000..490b9c8 --- /dev/null +++ b/CourseManagement.ApiGateway/ocelot.json @@ -0,0 +1,56 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/course-management", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 8081 + }, + { + "Host": "localhost", + "Port": 8082 + }, + { + "Host": "localhost", + "Port": 8083 + } + ], + "UpstreamPathTemplate": "/course-management", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "QueryBased", + "Key": "course-api" + } + }, + { + "DownstreamPathTemplate": "/health", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 8081 + }, + { + "Host": "localhost", + "Port": 8082 + }, + { + "Host": "localhost", + "Port": 8083 + } + ], + "UpstreamPathTemplate": "/health", + "UpstreamHttpMethod": [ "GET" ], + "Priority": 1, + "LoadBalancerOptions": { + "Type": "QueryBased", + "Key": "course-api-health" + } + } + ], + "GlobalConfiguration": { + "BaseUrl": "https://localhost:5000" + } +} \ No newline at end of file diff --git a/CourseManagement.ApiService/Controllers/CourseController.cs b/CourseManagement.ApiService/Controllers/CourseController.cs new file mode 100644 index 0000000..cb9b303 --- /dev/null +++ b/CourseManagement.ApiService/Controllers/CourseController.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Mvc; +using CourseManagement.ApiService.Dto; +using CourseManagement.ApiService.Services; + +namespace CourseManagement.ApiService.Controllers; + +/// +/// Контроллер для сущности типа Курс +/// +/// Логгер +/// Сервис для сущности типа Курс +[ApiController] +[Route("course-management")] +public class CourseController(ILogger logger, CourseService courseService) : ControllerBase +{ + /// + /// Обработчик GET-запроса на генерацию курса + /// + /// Идентификатор курса + /// Сгенерированный курс + [HttpGet] + public async Task> GetCourse(int? id) + { + logger.LogInformation("Processing request for course {ResourceId}", id); + + var course = await courseService.GetCourse(id ?? 0); + + return course != null ? Ok(course) : Problem("Internal server error", statusCode: 500); + } +} \ No newline at end of file diff --git a/CourseManagement.ApiService/CourseManagement.ApiService.csproj b/CourseManagement.ApiService/CourseManagement.ApiService.csproj new file mode 100644 index 0000000..b87ee4f --- /dev/null +++ b/CourseManagement.ApiService/CourseManagement.ApiService.csproj @@ -0,0 +1,21 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/CourseManagement.ApiService/Dto/CourseDto.cs b/CourseManagement.ApiService/Dto/CourseDto.cs new file mode 100644 index 0000000..cf920da --- /dev/null +++ b/CourseManagement.ApiService/Dto/CourseDto.cs @@ -0,0 +1,70 @@ +using System.Text.Json.Serialization; + +namespace CourseManagement.ApiService.Dto; + + +/// +/// DTO для сущности типа курс +/// +public class CourseDto +{ + /// + /// Идентификатор курса + /// + [JsonPropertyName("id")] + public int Id { get; set; } + + /// + /// Название курса + /// + [JsonPropertyName("title")] + public string Title { get; set; } = string.Empty; + + /// + /// Лектор + /// + [JsonPropertyName("lector")] + public string Lector { get; set; } = string.Empty; + + /// + /// Дата начала курса + /// + [JsonPropertyName("startDate")] + public DateOnly StartDate { get; set; } + + /// + /// Дата окончания курса + /// + [JsonPropertyName("endDate")] + public DateOnly EndDate { get; set; } + + /// + /// Максимальное число студентов для курса + /// + [JsonPropertyName("maxStudents")] + public int MaxStudents { get; set; } + + /// + /// Текущее число студентов курса + /// + [JsonPropertyName("enrolledStudents")] + public int EnrolledStudents { get; set; } + + /// + /// Выдача сертификата + /// + [JsonPropertyName("hasSertificate")] + public bool HasSertificate { get; set; } + + /// + /// Стоимость курса + /// + [JsonPropertyName("price")] + public decimal Price { get; set; } + + /// + /// Рейтинг + /// + [JsonPropertyName("rating")] + public int Rating { get; set; } +} diff --git a/CourseManagement.ApiService/Program.cs b/CourseManagement.ApiService/Program.cs new file mode 100644 index 0000000..180b9f0 --- /dev/null +++ b/CourseManagement.ApiService/Program.cs @@ -0,0 +1,43 @@ +using CourseManagement.ApiService.Dto; +using CourseManagement.ApiService.Services; + +var builder = WebApplication.CreateBuilder(args); + +// Add service defaults +builder.AddServiceDefaults(); + +// Redis +builder.AddRedisDistributedCache("course-cache"); + +// Add services to the container +builder.Services.AddProblemDetails(); +builder.Services.AddOpenApi(); + +// Контроллеры +builder.Services.AddControllers(); + +// Генератор курсов +builder.Services.AddSingleton(); + +// Сервис для взаимодействия с кэшем +builder.Services.AddSingleton>(); + +// Сервис для сущности типа Курс +builder.Services.AddSingleton(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline +app.UseExceptionHandler(); + +// Mapping +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi(); +} + +app.MapControllers(); + +app.MapDefaultEndpoints(); + +app.Run(); \ No newline at end of file diff --git a/CourseManagement.ApiService/Properties/launchSettings.json b/CourseManagement.ApiService/Properties/launchSettings.json new file mode 100644 index 0000000..e237496 --- /dev/null +++ b/CourseManagement.ApiService/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5329", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7170;http://localhost:5329", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CourseManagement.ApiService/Services/CacheService.cs b/CourseManagement.ApiService/Services/CacheService.cs new file mode 100644 index 0000000..ec6710b --- /dev/null +++ b/CourseManagement.ApiService/Services/CacheService.cs @@ -0,0 +1,77 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Distributed; + +namespace CourseManagement.ApiService.Services; + +/// +/// Сервис для взаимодействия с кэшем +/// +/// Логгер +/// Кэш +public class CacheService(ILogger> logger, IDistributedCache cache) +{ + /// + /// Время жизни данных в кэше + /// + private static readonly double _cacheDuration = 5; + + /// + /// Асинхронный метод для извлечения данных из кэша + /// + /// Ключ для сущности + /// Идентификатор объекта + /// Объект или null при его отсутствии + public async Task FetchAsync(string key, int id) + { + var cacheKey = $"{key}:{id}"; + + try + { + var cached = await cache.GetStringAsync(cacheKey); + if (cached != null) + { + var obj = JsonSerializer.Deserialize(cached); + + logger.LogInformation("Cache hit for object {ResourceId}", id); + + return obj; + } + + logger.LogInformation("Cache miss for object {ResourceId}", id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Сache is unavailable"); + } + + return default; + } + + /// + /// Асинхронный метод для внесения данных в кэш + /// + /// Ключ для сущности + /// Идентификатор объекта + /// Объект + public async Task StoreAsync(string key, int id, T obj) + { + var cacheKey = $"{key}:{id}"; + + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_cacheDuration) + }; + + try + { + var serialized = JsonSerializer.Serialize(obj); + await cache.SetStringAsync(cacheKey, serialized, options); + logger.LogInformation("Object {ResourceId} cached", id); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Сache is unavailable"); + } + + } +} diff --git a/CourseManagement.ApiService/Services/CourseGenerator.cs b/CourseManagement.ApiService/Services/CourseGenerator.cs new file mode 100644 index 0000000..f462eac --- /dev/null +++ b/CourseManagement.ApiService/Services/CourseGenerator.cs @@ -0,0 +1,81 @@ +using Bogus; +using CourseManagement.ApiService.Dto; + +namespace CourseManagement.ApiService.Services; + +/// +/// Генератор для сущности типа Курс +/// +/// Логгер +public class CourseGenerator(ILogger logger) +{ + /// + /// Список названий курсов + /// + private static readonly string[] _courseTitles = { + "Разработка корпоративных приложений", + "Алгоритмы и структуры данных", + "Базы данных", + "Веб-разработка", + "Машинное обучение", + "Основы информационной безопасности", + "Математический анализ", + "Линейная алгебра и геометрия", + "Математическая статистика", + "Теория вероятностей", + "Физика", + "Микроэкономика", + "Макроэкономика", + "Нейронные сети и глубокое обучение", + "Сети и системы передачи информации", + "Философия", + "История России", + "Дискретная математика", + "Прикладное программирование", + "Методы оптимизации", + "Теория графов", + "Технологии программирования", + "Основы веб-приложений", + "Безопасность вычислительных сетей", + "Низкоуровневое программирование", + "Системное программирование", + "Криптография", + "Криптопротоколы", + "Жизненный цикл", + "Цифровая обработка сигналов", + "Цифровая обработка изображений", + "Основы программиования", + "Объектно-ориентированное программирование", + "Форензика", + "Компьютерная алгебра", + }; + + /// + /// Экземпляр генератора данных + /// + private static readonly Faker _courseFaker = new Faker("ru") + .RuleFor(c => c.Title, f => f.PickRandom(_courseTitles)) + .RuleFor(c => c.Lector, f => f.Name.FullName()) + .RuleFor(c => c.StartDate, f => DateOnly.FromDateTime(f.Date.Future(1))) + .RuleFor(c => c.EndDate, (f, c) => c.StartDate.AddMonths(f.Random.Int(1, 6))) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 100)) + .RuleFor(c => c.EnrolledStudents, (f, c) => f.Random.Int(0, c.MaxStudents)) + .RuleFor(c => c.HasSertificate, f => f.Random.Bool()) + .RuleFor(c => c.Price, f => f.Finance.Amount(5000, 100000, 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + /// + /// Метод для генерации одного экземпляра сущности типа Курс + /// + /// Идентификатор курса + /// Курс + public CourseDto GenerateOne(int? id = null) + { + var course = _courseFaker.Generate(); + course.Id = id ?? new Randomizer().Int(1, 100000); + + logger.LogInformation("Course {ResourceId} generated", id); + + return course; + } +} \ No newline at end of file diff --git a/CourseManagement.ApiService/Services/CourseService.cs b/CourseManagement.ApiService/Services/CourseService.cs new file mode 100644 index 0000000..91a7bc7 --- /dev/null +++ b/CourseManagement.ApiService/Services/CourseService.cs @@ -0,0 +1,44 @@ +using CourseManagement.ApiService.Dto; + +namespace CourseManagement.ApiService.Services; + +/// +/// Сервис для сущности типа Курс +/// +/// Логгер +/// Генератор курсов +/// Сервис для взаимодействия с кэшем +public class CourseService(ILogger logger, CourseGenerator generator, CacheService cacheService) +{ + /// + /// Константа для ключа кэша + /// + private const string CacheKeyPrefix = "course"; + + /// + /// Метод для получения курса + /// + /// Идентификатор курса + /// Курс или null при ошибке + public async Task GetCourse(int id) + { + try + { + var course = await cacheService.FetchAsync(CacheKeyPrefix, id); + if (course != null) + return course; + + var newCourse = generator.GenerateOne(id); + + await cacheService.StoreAsync(CacheKeyPrefix, id, newCourse); + + return newCourse; + } + catch (Exception ex) + { + logger.LogError(ex, "Error processing course {ResourceId}", id); + } + + return null; + } +} diff --git a/CourseManagement.ApiService/appsettings.Development.json b/CourseManagement.ApiService/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CourseManagement.ApiService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseManagement.ApiService/appsettings.json b/CourseManagement.ApiService/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/CourseManagement.ApiService/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CourseManagement.AppHost/AppHost.cs b/CourseManagement.AppHost/AppHost.cs new file mode 100644 index 0000000..1557e63 --- /dev/null +++ b/CourseManagement.AppHost/AppHost.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Configuration; + +var builder = DistributedApplication.CreateBuilder(args); + + +// Configuration +var apiServiceConfig = builder.Configuration.GetSection("ApiService"); +var ports = apiServiceConfig.GetSection("Ports").Get>() ?? []; + +var apiGatewayConfig = builder.Configuration.GetSection("ApiGateway"); +var gatewayPort = apiGatewayConfig.GetValue("Port"); + + +// Cache (Redis) +var redis = builder.AddRedis("course-cache") + .WithRedisInsight(containerName: "course-insight") + .WithDataVolume(); + + +// API services (Backend) +var apiServices = new List>(); + +var serviceId = 1; +foreach(var port in ports) +{ + apiServices.Add(builder.AddProject($"course-api-{serviceId++}") + .WithReference(redis) + .WithHttpHealthCheck("/health") + .WithHttpsEndpoint(port: port, name: "course-api-endpoint", isProxied: false) + .WithExternalHttpEndpoints()); +} + + +// API Gateway (Ocelot) +var apiGateway = builder.AddProject("course-gateway") + .WithHttpsEndpoint(port: gatewayPort, name: "course-gateway-endpoint", isProxied: false) + .WithExternalHttpEndpoints() + .WithHttpHealthCheck("/health"); + +foreach (var apiService in apiServices) +{ + apiGateway.WaitFor(apiService); +} + + +// Client (Frontend) +builder.AddProject("course-wasm") + .WithExternalHttpEndpoints() + .WithHttpHealthCheck("/health") + .WithReference(apiGateway) + .WaitFor(apiGateway); + + +builder.Build().Run(); diff --git a/CourseManagement.AppHost/CourseManagement.AppHost.csproj b/CourseManagement.AppHost/CourseManagement.AppHost.csproj new file mode 100644 index 0000000..b84cfb4 --- /dev/null +++ b/CourseManagement.AppHost/CourseManagement.AppHost.csproj @@ -0,0 +1,21 @@ + + + + Exe + net10.0 + enable + enable + 9bbc0bf3-e529-4a0f-833b-49b80c01c009 + + + + + + + + + + + + + diff --git a/CourseManagement.AppHost/Properties/launchSettings.json b/CourseManagement.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..8bba3b8 --- /dev/null +++ b/CourseManagement.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17286;http://localhost:15040", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21283", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23150", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22100" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15040", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19011", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18011", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20240" + } + } + } +} diff --git a/CourseManagement.AppHost/appsettings.Development.json b/CourseManagement.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CourseManagement.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseManagement.AppHost/appsettings.json b/CourseManagement.AppHost/appsettings.json new file mode 100644 index 0000000..3c4261d --- /dev/null +++ b/CourseManagement.AppHost/appsettings.json @@ -0,0 +1,19 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "ApiService": { + "Ports": [ + 8081, + 8082, + 8083 + ] + }, + "ApiGateway": { + "Port": 5000 + } +} diff --git a/CourseManagement.ServiceDefaults/CourseManagement.ServiceDefaults.csproj b/CourseManagement.ServiceDefaults/CourseManagement.ServiceDefaults.csproj new file mode 100644 index 0000000..eeb71e3 --- /dev/null +++ b/CourseManagement.ServiceDefaults/CourseManagement.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CourseManagement.ServiceDefaults/Extensions.cs b/CourseManagement.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..b72c875 --- /dev/null +++ b/CourseManagement.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common 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 +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + 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(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // 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(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/CourseManagement.sln b/CourseManagement.sln new file mode 100644 index 0000000..b3ba5bd --- /dev/null +++ b/CourseManagement.sln @@ -0,0 +1,49 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 18 +VisualStudioVersion = 18.4.11506.43 +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}") = "CourseManagement.ApiGateway", "CourseManagement.ApiGateway\CourseManagement.ApiGateway.csproj", "{E40206AD-E9A9-D006-03E9-7E4AF186D09E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseManagement.ApiService", "CourseManagement.ApiService\CourseManagement.ApiService.csproj", "{177A7026-640A-B562-C970-E54A3E1808C0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseManagement.AppHost", "CourseManagement.AppHost\CourseManagement.AppHost.csproj", "{6FA675B1-94EE-1C38-B6D5-9B8D1B49AF80}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseManagement.ServiceDefaults", "CourseManagement.ServiceDefaults\CourseManagement.ServiceDefaults.csproj", "{6C7E991E-FC79-5A4B-8EC0-AF85D0B47940}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {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 + {E40206AD-E9A9-D006-03E9-7E4AF186D09E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E40206AD-E9A9-D006-03E9-7E4AF186D09E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E40206AD-E9A9-D006-03E9-7E4AF186D09E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E40206AD-E9A9-D006-03E9-7E4AF186D09E}.Release|Any CPU.Build.0 = Release|Any CPU + {177A7026-640A-B562-C970-E54A3E1808C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {177A7026-640A-B562-C970-E54A3E1808C0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {177A7026-640A-B562-C970-E54A3E1808C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {177A7026-640A-B562-C970-E54A3E1808C0}.Release|Any CPU.Build.0 = Release|Any CPU + {6FA675B1-94EE-1C38-B6D5-9B8D1B49AF80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6FA675B1-94EE-1C38-B6D5-9B8D1B49AF80}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6FA675B1-94EE-1C38-B6D5-9B8D1B49AF80}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6FA675B1-94EE-1C38-B6D5-9B8D1B49AF80}.Release|Any CPU.Build.0 = Release|Any CPU + {6C7E991E-FC79-5A4B-8EC0-AF85D0B47940}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6C7E991E-FC79-5A4B-8EC0-AF85D0B47940}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6C7E991E-FC79-5A4B-8EC0-AF85D0B47940}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6C7E991E-FC79-5A4B-8EC0-AF85D0B47940}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index dcaa5eb..e4cae4d 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,18 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). +# Томашайтис Павел 6513 (вариант 52) +--- +## Учебный курс + +**Внесённые изменения:** +- [x] Cервис генерации контрактов на основе Bogus +- [x] Кеширование при помощи IDistributedCache и Redis +- [x] Сервис для взаимодействия с кешем +- [x] Структурное логирование сервисов +- [x] Оркестрация Aspire +- [x] Поддержка работы с несколькими репликами сервиса генерации +- [x] Api Gateway Ocelot +- [x] QueryBased балансировщик нагрузки + +image + +image