diff --git a/.gitignore b/.gitignore index ce892922..5afb6ccc 100644 --- a/.gitignore +++ b/.gitignore @@ -416,3 +416,6 @@ FodyWeavers.xsd *.msix *.msm *.msp + +# User-specific +.DS_Store diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100755 index 00000000..38c81e1b --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Api.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs b/Api.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs new file mode 100755 index 00000000..14ff3aab --- /dev/null +++ b/Api.Gateway/LoadBalancing/WeightedRandomLoadBalancer.cs @@ -0,0 +1,38 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.LoadBalancing; + +/// +/// Балансировка случайным образом с весами +/// +/// Функция получения списка сервисов +/// Конфигурация приложения +public class WeightedRandomLoadBalancer( + Func>> services, + IConfiguration configuration) : ILoadBalancer +{ + private readonly int[] _frequencies = configuration.GetSection("LoadBalancing:Weights").Get() ?? [5, 4, 3, 2, 1]; + + public string Type => nameof(WeightedRandomLoadBalancer); + + public async Task> LeaseAsync(HttpContext httpContext) + { + var availableServices = await services(); + + if (availableServices.Count == 0) + throw new InvalidOperationException("No available downstream services"); + + var values = Enumerable.Range(1, availableServices.Count) + .Zip(_frequencies, (val, freq) => Enumerable.Repeat(val, freq)) + .SelectMany(x => x) + .ToArray(); + + Random.Shared.Shuffle(values); + + return new OkResponse(availableServices[values.First() - 1].HostAndPort); + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100755 index 00000000..3b61837b --- /dev/null +++ b/Api.Gateway/Program.cs @@ -0,0 +1,34 @@ +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Api.Gateway.LoadBalancing; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); +builder.Services.AddOcelot() + .AddCustomLoadBalancer((sp, _, provider) => + new WeightedRandomLoadBalancer(provider.GetAsync, sp.GetRequiredService())); + +var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get() ?? []; + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.WithOrigins(allowedOrigins) + .AllowAnyHeader() + .WithMethods("GET"); + }); +}); + +var app = builder.Build(); + +app.UseCors(); + +app.MapDefaultEndpoints(); + +await app.UseOcelot(); + +app.Run(); diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json new file mode 100755 index 00000000..27cd238f --- /dev/null +++ b/Api.Gateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:51762", + "sslPort": 44308 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5297", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7297;http://localhost:5297", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Api.Gateway/appsettings.Development.json b/Api.Gateway/appsettings.Development.json new file mode 100755 index 00000000..ff66ba6b --- /dev/null +++ b/Api.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Api.Gateway/appsettings.json b/Api.Gateway/appsettings.json new file mode 100755 index 00000000..f656df03 --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Cors": { + "AllowedOrigins": [ + "http://localhost:5127", + "https://localhost:7282" + ] + }, + "LoadBalancing": { + "Weights": [ 5, 4, 3, 2, 1 ] + } +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100755 index 00000000..e0f53b61 --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -0,0 +1,35 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/api/courses", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5213 + }, + { + "Host": "localhost", + "Port": 5214 + }, + { + "Host": "localhost", + "Port": 5215 + }, + { + "Host": "localhost", + "Port": 5216 + }, + { + "Host": "localhost", + "Port": 5217 + } + ], + "UpstreamPathTemplate": "/courses", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "WeightedRandomLoadBalancer" + } + } + ] +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor old mode 100644 new mode 100755 index 661f1181..a2c25279 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №3 "Интеграционное тестирование" + Вариант №37 "Учебный курс" + Выполнена Вольговым Даниилом 6513 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json old mode 100644 new mode 100755 index 0d824ea7..60120ec3 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,7 +12,7 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "applicationUrl": "http://localhost:5127", "environmentVariables": { @@ -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 old mode 100644 new mode 100755 index d1fe7ab3..5cd94264 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7297/courses" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln old mode 100644 new mode 100755 index cb48241d..57bad120 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,25 +1,61 @@ - -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 + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36811.4 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost", "CourseApp\CourseApp.AppHost\CourseApp.AppHost.csproj", "{B51DE59B-BAF5-434D-B2AB-05002DF1BA24}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.ServiceDefaults", "CourseApp\CourseApp.ServiceDefaults\CourseApp.ServiceDefaults.csproj", "{064D02F8-AA28-8AA3-C1DB-6440761E6CB3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.Api", "CourseApp.Api\CourseApp.Api.csproj", "{2077B3EC-232D-D44F-72B9-3B84AA8AE54F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost.Tests", "CourseApp\CourseApp.AppHost.Tests\CourseApp.AppHost.Tests.csproj", "{5B3B2F7D-35EF-4EBB-9AD2-12136E833FDB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.FileService", "CourseApp.FileService\CourseApp.FileService.csproj", "{FC9159EC-39F4-3146-F993-EF1EB3A20385}" +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 + {B51DE59B-BAF5-434D-B2AB-05002DF1BA24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B51DE59B-BAF5-434D-B2AB-05002DF1BA24}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B51DE59B-BAF5-434D-B2AB-05002DF1BA24}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B51DE59B-BAF5-434D-B2AB-05002DF1BA24}.Release|Any CPU.Build.0 = Release|Any CPU + {064D02F8-AA28-8AA3-C1DB-6440761E6CB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {064D02F8-AA28-8AA3-C1DB-6440761E6CB3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {064D02F8-AA28-8AA3-C1DB-6440761E6CB3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {064D02F8-AA28-8AA3-C1DB-6440761E6CB3}.Release|Any CPU.Build.0 = Release|Any CPU + {2077B3EC-232D-D44F-72B9-3B84AA8AE54F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2077B3EC-232D-D44F-72B9-3B84AA8AE54F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2077B3EC-232D-D44F-72B9-3B84AA8AE54F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2077B3EC-232D-D44F-72B9-3B84AA8AE54F}.Release|Any CPU.Build.0 = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU + {5B3B2F7D-35EF-4EBB-9AD2-12136E833FDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5B3B2F7D-35EF-4EBB-9AD2-12136E833FDB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5B3B2F7D-35EF-4EBB-9AD2-12136E833FDB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5B3B2F7D-35EF-4EBB-9AD2-12136E833FDB}.Release|Any CPU.Build.0 = Release|Any CPU + {FC9159EC-39F4-3146-F993-EF1EB3A20385}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FC9159EC-39F4-3146-F993-EF1EB3A20385}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FC9159EC-39F4-3146-F993-EF1EB3A20385}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FC9159EC-39F4-3146-F993-EF1EB3A20385}.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/CourseApp.Api/CourseApp.Api.csproj b/CourseApp.Api/CourseApp.Api.csproj new file mode 100755 index 00000000..b36dbafc --- /dev/null +++ b/CourseApp.Api/CourseApp.Api.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/CourseApp.Api/Generators/CourseGenerator.cs b/CourseApp.Api/Generators/CourseGenerator.cs new file mode 100755 index 00000000..f96ea9e6 --- /dev/null +++ b/CourseApp.Api/Generators/CourseGenerator.cs @@ -0,0 +1,73 @@ +using Bogus; +using CourseApp.Api.Models; + +namespace CourseApp.Api.Generators; + +/// +/// Генератор учебных курсов на основе Bogus +/// +public static class CourseGenerator +{ + private static readonly string[] _courseNames = + [ + "Основы программирования", + "Базы данных", + "Веб-разработка", + "Машинное обучение", + "Алгоритмы и структуры данных", + "Компьютерные сети", + "Операционные системы", + "Информационная безопасность", + "Мобильная разработка", + "Облачные технологии", + "Искусственный интеллект", + "Анализ данных", + "DevOps-практики" + ]; + + private static readonly Faker _faker = new Faker("ru") + .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) + .RuleFor(c => c.TeacherFullName, f => + { + var gender = f.Random.Bool() ? Bogus.DataSets.Name.Gender.Male : Bogus.DataSets.Name.Gender.Female; + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} {GeneratePatronymic(f.Name.FirstName(Bogus.DataSets.Name.Gender.Male), gender)}"; + }) + .RuleFor(c => c.StartDate, f => + DateOnly.FromDateTime(f.Date.Between(DateTime.Now, DateTime.Now.AddMonths(3)))) + .RuleFor(c => c.EndDate, (f, c) => + c.StartDate.AddDays(f.Random.Int(30, 180))) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 100)) + .RuleFor(c => c.CurrentStudents, (f, c) => f.Random.Int(0, c.MaxStudents)) + .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) + .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(5000m, 150000m), 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + /// + /// Генерация отчества из мужского имени + /// + /// Мужское имя + /// Пол преподавателя + private static string GeneratePatronymic(string maleFirstName, Bogus.DataSets.Name.Gender gender) + { + var isMale = gender == Bogus.DataSets.Name.Gender.Male; + + if (maleFirstName.EndsWith('ь') || maleFirstName.EndsWith('й')) + return maleFirstName[..^1] + (isMale ? "евич" : "евна"); + + if (maleFirstName.EndsWith('а') || maleFirstName.EndsWith('я')) + return maleFirstName[..^1] + (isMale ? "ич" : "ична"); + + return maleFirstName + (isMale ? "ович" : "овна"); + } + + /// + /// Генерация учебного курса с указанным идентификатором + /// + /// Идентификатор курса + public static Course Generate(int id) + { + var course = _faker.Generate(); + course.Id = id; + return course; + } +} diff --git a/CourseApp.Api/Messaging/IProducerService.cs b/CourseApp.Api/Messaging/IProducerService.cs new file mode 100755 index 00000000..36eb65e8 --- /dev/null +++ b/CourseApp.Api/Messaging/IProducerService.cs @@ -0,0 +1,15 @@ +using CourseApp.Api.Models; + +namespace CourseApp.Api.Messaging; + +/// +/// Интерфейс продюсера для отправки сгенерированных учебных курсов в брокер сообщений +/// +public interface IProducerService +{ + /// + /// Сериализует курс в JSON и отправляет его в брокер + /// + /// Сгенерированный учебный курс + public Task SendMessage(Course course); +} diff --git a/CourseApp.Api/Messaging/SqsProducerService.cs b/CourseApp.Api/Messaging/SqsProducerService.cs new file mode 100755 index 00000000..9d704cd7 --- /dev/null +++ b/CourseApp.Api/Messaging/SqsProducerService.cs @@ -0,0 +1,44 @@ +using System.Net; +using System.Text.Json; +using Amazon.SQS; +using CourseApp.Api.Models; + +namespace CourseApp.Api.Messaging; + +/// +/// Реализация продюсера на базе AWS SQS +/// +/// Клиент SQS, поднятый AWS SDK через LocalStack +/// Конфигурация (имя очереди берётся из CloudFormation Outputs) +/// Логгер +public sealed class SqsProducerService( + IAmazonSQS client, + IConfiguration configuration, + ILogger logger) : IProducerService +{ + private static readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + /// + public async Task SendMessage(Course course) + { + try + { + var json = JsonSerializer.Serialize(course, _jsonOptions); + var response = await client.SendMessageAsync(_queueName, json); + if (response.HttpStatusCode == HttpStatusCode.OK) + logger.LogInformation("Course {Id} was sent to SQS", course.Id); + else + throw new InvalidOperationException($"SQS returned {response.HttpStatusCode}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Unable to send course {Id} through SQS", course.Id); + } + } +} diff --git a/CourseApp.Api/Models/Course.cs b/CourseApp.Api/Models/Course.cs new file mode 100755 index 00000000..ea68a99a --- /dev/null +++ b/CourseApp.Api/Models/Course.cs @@ -0,0 +1,57 @@ +namespace CourseApp.Api.Models; + +/// +/// Учебный курс +/// +public class Course +{ + /// + /// Идентификатор в системе + /// + public int Id { get; set; } + + /// + /// Наименование курса + /// + public required string Name { get; set; } + + /// + /// ФИО преподавателя + /// + public required string TeacherFullName { get; set; } + + /// + /// Дата начала + /// + public DateOnly StartDate { get; set; } + + /// + /// Дата окончания + /// + public DateOnly EndDate { get; set; } + + /// + /// Максимальное число студентов + /// + public int MaxStudents { get; set; } + + /// + /// Текущее число студентов + /// + public int CurrentStudents { get; set; } + + /// + /// Выдача сертификата + /// + public bool HasCertificate { get; set; } + + /// + /// Стоимость + /// + public decimal Price { get; set; } + + /// + /// Рейтинг + /// + public int Rating { get; set; } +} diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs new file mode 100755 index 00000000..df1d35d9 --- /dev/null +++ b/CourseApp.Api/Program.cs @@ -0,0 +1,23 @@ +using Amazon.SQS; +using CourseApp.Api.Messaging; +using CourseApp.Api.Services; +using LocalStack.Client.Extensions; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapDefaultEndpoints(); + +app.MapGet("/api/courses", async (int id, ICourseService courseService) => + Results.Ok(await courseService.GetCourse(id))); + +app.Run(); diff --git a/CourseApp.Api/Properties/launchSettings.json b/CourseApp.Api/Properties/launchSettings.json new file mode 100755 index 00000000..64f00edb --- /dev/null +++ b/CourseApp.Api/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:11583", + "sslPort": 44345 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5213", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7156;http://localhost:5213", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CourseApp.Api/Services/CourseService.cs b/CourseApp.Api/Services/CourseService.cs new file mode 100755 index 00000000..e8a84b53 --- /dev/null +++ b/CourseApp.Api/Services/CourseService.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using CourseApp.Api.Generators; +using CourseApp.Api.Messaging; +using CourseApp.Api.Models; +using Microsoft.Extensions.Caching.Distributed; + +namespace CourseApp.Api.Services; + +/// +/// Сервис учебных курсов с кэшированием в Redis и публикацией в SQS +/// +/// Распределённый кэш (Redis) +/// Продюсер сообщений (SQS) +/// Конфигурация приложения +/// Логгер +public sealed class CourseService( + IDistributedCache cache, + IProducerService producer, + IConfiguration configuration, + ILogger logger) : ICourseService +{ + private const string CacheKeyPrefix = "course:"; + + private readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes( + configuration.GetValue("Cache:ExpirationMinutes")); + + /// + /// Получение учебного курса по идентификатору с кэшированием и публикацией в очередь + /// + /// Идентификатор курса + public async Task GetCourse(int id) + { + var cachedCourse = await TryGetFromCache(id); + if (cachedCourse is not null) + { + logger.LogInformation("Cache hit for course {Id}", id); + return cachedCourse; + } + + logger.LogInformation("Cache miss for course {Id}", id); + var course = CourseGenerator.Generate(id); + logger.LogInformation("Generated course {@Course}", course); + + await Task.WhenAll(TrySetToCache(id, course), producer.SendMessage(course)); + return course; + } + + private async Task TryGetFromCache(int id) + { + try + { + var data = await cache.GetStringAsync(CacheKeyPrefix + id); + return data is null ? null : JsonSerializer.Deserialize(data); + } + catch (Exception ex) + { + logger.LogError(ex, "Error reading course {Id} from cache", id); + return null; + } + } + + private async Task TrySetToCache(int id, Course course) + { + try + { + var data = JsonSerializer.Serialize(course); + var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = _cacheExpiration }; + await cache.SetStringAsync(CacheKeyPrefix + id, data, options); + logger.LogInformation("Course {Id} saved to cache", id); + } + catch (Exception ex) + { + logger.LogError(ex, "Error saving course {Id} to cache", id); + } + } +} diff --git a/CourseApp.Api/Services/ICourseService.cs b/CourseApp.Api/Services/ICourseService.cs new file mode 100755 index 00000000..4a9695e6 --- /dev/null +++ b/CourseApp.Api/Services/ICourseService.cs @@ -0,0 +1,15 @@ +using CourseApp.Api.Models; + +namespace CourseApp.Api.Services; + +/// +/// Интерфейс сервиса учебных курсов +/// +public interface ICourseService +{ + /// + /// Получение учебного курса по идентификатору + /// + /// Идентификатор курса + public Task GetCourse(int id); +} diff --git a/CourseApp.Api/appsettings.Development.json b/CourseApp.Api/appsettings.Development.json new file mode 100755 index 00000000..ff66ba6b --- /dev/null +++ b/CourseApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp.Api/appsettings.json b/CourseApp.Api/appsettings.json new file mode 100755 index 00000000..4b07986a --- /dev/null +++ b/CourseApp.Api/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Cache": { + "ExpirationMinutes": 5 + } +} diff --git a/CourseApp.FileService/Controllers/S3StorageController.cs b/CourseApp.FileService/Controllers/S3StorageController.cs new file mode 100755 index 00000000..a6635f9b --- /dev/null +++ b/CourseApp.FileService/Controllers/S3StorageController.cs @@ -0,0 +1,52 @@ +using System.Text.Json.Nodes; +using CourseApp.FileService.Storage; +using Microsoft.AspNetCore.Mvc; + +namespace CourseApp.FileService.Controllers; + +/// +/// HTTP-фасад над S3 для интеграционных тестов и ручной отладки +/// +/// Служба для работы с S3 +/// Логгер +[ApiController] +[Route("api/s3")] +public sealed class S3StorageController(IS3Service s3Service, ILogger logger) : ControllerBase +{ + /// + /// Возвращает список всех ключей в бакете + /// + /// 200 с массивом ключей; 500 при ошибке + [HttpGet] + public async Task>> ListFiles() + { + try + { + return Ok(await s3Service.GetFileList()); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to list bucket contents"); + return StatusCode(500, ex.Message); + } + } + + /// + /// Возвращает JSON-документ по ключу объекта + /// + /// Ключ объекта в S3 (например, course_42.json) + /// 200 с телом JSON; 500 при ошибке + [HttpGet("{key}")] + public async Task> GetFile(string key) + { + try + { + return Ok(await s3Service.DownloadFile(key)); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to download {Key}", key); + return StatusCode(500, ex.Message); + } + } +} diff --git a/CourseApp.FileService/CourseApp.FileService.csproj b/CourseApp.FileService/CourseApp.FileService.csproj new file mode 100755 index 00000000..7deaa72d --- /dev/null +++ b/CourseApp.FileService/CourseApp.FileService.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/CourseApp.FileService/Messaging/SqsConsumerService.cs b/CourseApp.FileService/Messaging/SqsConsumerService.cs new file mode 100755 index 00000000..95a6a9c0 --- /dev/null +++ b/CourseApp.FileService/Messaging/SqsConsumerService.cs @@ -0,0 +1,64 @@ +using Amazon.SQS; +using Amazon.SQS.Model; +using CourseApp.FileService.Storage; + +namespace CourseApp.FileService.Messaging; + +/// +/// Фоновая служба, читающая SQS батчами и складывающая курсы в S3. +/// Перед стартом цикла гарантирует существование бакета. +/// +/// Клиент SQS +/// Фабрика scope для получения IS3Service на каждое сообщение +/// Конфигурация (имя очереди) +/// Логгер +public sealed class SqsConsumerService( + IAmazonSQS sqsClient, + IServiceScopeFactory scopeFactory, + IConfiguration configuration, + ILogger logger) : BackgroundService +{ + private readonly string _queueName = configuration["AWS:Resources:SQSQueueName"] + ?? throw new KeyNotFoundException("SQS queue name was not found in configuration"); + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using (var startupScope = scopeFactory.CreateScope()) + { + var s3 = startupScope.ServiceProvider.GetRequiredService(); + await s3.EnsureBucketExists(); + } + + logger.LogInformation("SQS consumer started, polling {Queue}", _queueName); + + while (!stoppingToken.IsCancellationRequested) + { + var response = await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest + { + QueueUrl = _queueName, + MaxNumberOfMessages = 10, + WaitTimeSeconds = 5 + }, stoppingToken); + + if (response?.Messages is null || response.Messages.Count == 0) + continue; + + foreach (var message in response.Messages) + { + try + { + using var scope = scopeFactory.CreateScope(); + var s3 = scope.ServiceProvider.GetRequiredService(); + await s3.UploadFile(message.Body); + + await sqsClient.DeleteMessageAsync(_queueName, message.ReceiptHandle, stoppingToken); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to process SQS message {MessageId}", message.MessageId); + } + } + } + } +} diff --git a/CourseApp.FileService/Program.cs b/CourseApp.FileService/Program.cs new file mode 100755 index 00000000..163fdcfd --- /dev/null +++ b/CourseApp.FileService/Program.cs @@ -0,0 +1,36 @@ +using Amazon.S3; +using Amazon.SQS; +using CourseApp.FileService.Messaging; +using CourseApp.FileService.Storage; +using LocalStack.Client.Extensions; +using System.Reflection; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddSwaggerGen(options => +{ + var assembly = Assembly.GetExecutingAssembly(); + options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{assembly.GetName().Name}.xml")); +}); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.Services.AddAwsService(); +builder.Services.AddScoped(); +builder.Services.AddHostedService(); + +builder.Services.AddControllers(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.MapControllers(); +app.Run(); diff --git a/CourseApp.FileService/Properties/launchSettings.json b/CourseApp.FileService/Properties/launchSettings.json new file mode 100755 index 00000000..6cfd062e --- /dev/null +++ b/CourseApp.FileService/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:62294", + "sslPort": 44355, + "launchUrl": "swagger" + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5282", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "swagger" + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7251;http://localhost:5282", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "swagger" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CourseApp.FileService/Storage/IS3Service.cs b/CourseApp.FileService/Storage/IS3Service.cs new file mode 100755 index 00000000..f3165e83 --- /dev/null +++ b/CourseApp.FileService/Storage/IS3Service.cs @@ -0,0 +1,32 @@ +using System.Text.Json.Nodes; + +namespace CourseApp.FileService.Storage; + +/// +/// Интерфейс службы для манипуляции файлами курсов в объектном хранилище S3 +/// +public interface IS3Service +{ + /// + /// Загружает JSON курса в бакет под ключом course_{id}.json + /// + /// Сырое тело сообщения в формате JSON + /// true, если PUT прошёл успешно + public Task UploadFile(string fileData); + + /// + /// Возвращает список ключей всех объектов в бакете + /// + public Task> GetFileList(); + + /// + /// Скачивает объект из бакета и возвращает его как JsonNode + /// + /// Ключ объекта (например, course_42.json) + public Task DownloadFile(string key); + + /// + /// Создаёт бакет, если он ещё не существует + /// + public Task EnsureBucketExists(); +} diff --git a/CourseApp.FileService/Storage/S3Service.cs b/CourseApp.FileService/Storage/S3Service.cs new file mode 100755 index 00000000..6b1b0180 --- /dev/null +++ b/CourseApp.FileService/Storage/S3Service.cs @@ -0,0 +1,82 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Amazon.S3; +using Amazon.S3.Model; + +namespace CourseApp.FileService.Storage; + +/// +/// Реализация IS3Service на AWS SDK для S3 (через LocalStack) +/// +/// Клиент S3 +/// Конфигурация (имя бакета берётся из CloudFormation Outputs) +/// Логгер +public sealed class S3Service( + IAmazonS3 client, + IConfiguration configuration, + ILogger logger) : IS3Service +{ + private readonly string _bucketName = configuration["AWS:Resources:S3BucketName"] + ?? throw new KeyNotFoundException("S3 bucket name was not found in configuration"); + + /// + public async Task UploadFile(string fileData) + { + var rootNode = JsonNode.Parse(fileData) ?? throw new ArgumentException("Passed string is not a valid JSON"); + var id = (rootNode["id"] ?? rootNode["Id"])?.GetValue() + ?? throw new ArgumentException("Passed JSON has invalid structure"); + + using var stream = new MemoryStream(); + JsonSerializer.Serialize(stream, rootNode); + stream.Seek(0, SeekOrigin.Begin); + + var request = new PutObjectRequest + { + BucketName = _bucketName, + Key = $"course_{id}.json", + InputStream = stream, + ContentType = "application/json" + }; + + var response = await client.PutObjectAsync(request); + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to upload course {Id}: {Code}", id, response.HttpStatusCode); + return false; + } + logger.LogInformation("Uploaded course {Id} to bucket {Bucket}", id, _bucketName); + return true; + } + + /// + public async Task> GetFileList() + { + var keys = new List(); + var paginator = client.Paginators.ListObjectsV2(new ListObjectsV2Request { BucketName = _bucketName }); + await foreach (var response in paginator.Responses) + if (response?.S3Objects is { } objects) + keys.AddRange(objects.Where(o => o is not null).Select(o => o.Key)); + return keys; + } + + /// + public async Task DownloadFile(string key) + { + using var response = await client.GetObjectAsync(new GetObjectRequest { BucketName = _bucketName, Key = key }); + if (response.HttpStatusCode != HttpStatusCode.OK) + throw new InvalidOperationException($"Error downloading {key}: {response.HttpStatusCode}"); + + using var reader = new StreamReader(response.ResponseStream, Encoding.UTF8); + return JsonNode.Parse(await reader.ReadToEndAsync()) + ?? throw new InvalidOperationException($"Object {key} is not a valid JSON"); + } + + /// + public async Task EnsureBucketExists() + { + await client.EnsureBucketExistsAsync(_bucketName); + logger.LogInformation("Bucket {Bucket} existence ensured", _bucketName); + } +} diff --git a/CourseApp.FileService/appsettings.Development.json b/CourseApp.FileService/appsettings.Development.json new file mode 100755 index 00000000..ff66ba6b --- /dev/null +++ b/CourseApp.FileService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp.FileService/appsettings.json b/CourseApp.FileService/appsettings.json new file mode 100755 index 00000000..4d566948 --- /dev/null +++ b/CourseApp.FileService/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CourseApp/CourseApp.AppHost.Tests/CourseApp.AppHost.Tests.csproj b/CourseApp/CourseApp.AppHost.Tests/CourseApp.AppHost.Tests.csproj new file mode 100755 index 00000000..59fa045c --- /dev/null +++ b/CourseApp/CourseApp.AppHost.Tests/CourseApp.AppHost.Tests.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CourseApp/CourseApp.AppHost.Tests/IntegrationTest.cs b/CourseApp/CourseApp.AppHost.Tests/IntegrationTest.cs new file mode 100644 index 00000000..3f4d4f8e --- /dev/null +++ b/CourseApp/CourseApp.AppHost.Tests/IntegrationTest.cs @@ -0,0 +1,104 @@ +using Aspire.Hosting; +using CourseApp.Api.Models; +using Microsoft.Extensions.Logging; +using System.Text.Json; +using Xunit.Abstractions; + +namespace CourseApp.AppHost.Tests; + +/// +/// Интеграционные тесты пайплайна +/// +public sealed class IntegrationTest(ITestOutputHelper output) : IAsyncLifetime +{ + private DistributedApplication? _app; + private HttpClient? _gatewayClient; + private HttpClient? _sinkClient; + + private static readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + var builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + builder.Services.AddLogging(logging => + { + logging.AddXUnit(output); + logging.SetMinimumLevel(LogLevel.Debug); + logging.AddFilter("Aspire.Hosting.Dcp", LogLevel.Debug); + logging.AddFilter("Aspire.Hosting", LogLevel.Debug); + }); + _app = await builder.BuildAsync(cancellationToken); + await _app.StartAsync(cancellationToken); + _gatewayClient = _app.CreateHttpClient("api-gateway", "http"); + _sinkClient = _app.CreateHttpClient("courseapp-fileservice", "http"); + } + + /// + /// Главный happy-path: запрос к API кладёт сериализованный курс в S3 идентичным тому, что вернулся клиенту + /// + [Fact] + public async Task Pipeline_PutsGeneratedCourseToS3() + { + var random = new Random(); + var id = random.Next(1, 500); + using var gatewayResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + Assert.True(gatewayResponse.IsSuccessStatusCode); + + var apiCourse = JsonSerializer.Deserialize( + await gatewayResponse.Content.ReadAsStringAsync(), _jsonOptions); + + await Task.Delay(5000); + + using var s3Response = await _sinkClient!.GetAsync($"/api/s3/course_{id}.json"); + Assert.True(s3Response.IsSuccessStatusCode); + + var s3Course = JsonSerializer.Deserialize( + await s3Response.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(apiCourse); + Assert.NotNull(s3Course); + Assert.Equal(id, s3Course!.Id); + Assert.Equivalent(apiCourse, s3Course); + } + + /// + /// Идемпотентность: cache hit не публикует в SQS повторно. + /// Дважды зовём один и тот же id; в S3 должен лежать ровно один файл course_{id}.json + /// + [Fact] + public async Task Pipeline_CacheHitDoesNotDuplicateFile() + { + var random = new Random(); + var id = random.Next(1, 500); + using var firstResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + Assert.True(firstResponse.IsSuccessStatusCode); + + using var secondResponse = await _gatewayClient!.GetAsync($"/courses?id={id}"); + Assert.True(secondResponse.IsSuccessStatusCode); + + await Task.Delay(5000); + + using var listResponse = await _sinkClient!.GetAsync("/api/s3"); + Assert.True(listResponse.IsSuccessStatusCode); + + var keys = JsonSerializer.Deserialize>( + await listResponse.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(keys); + Assert.Single(keys!, key => key == $"course_{id}.json"); + } + + public async Task DisposeAsync() + { + if (_app is not null) + { + await _app.StopAsync(); + await _app.DisposeAsync(); + } + } +} diff --git a/CourseApp/CourseApp.AppHost/AppHost.cs b/CourseApp/CourseApp.AppHost/AppHost.cs new file mode 100755 index 00000000..916e074c --- /dev/null +++ b/CourseApp/CourseApp.AppHost/AppHost.cs @@ -0,0 +1,49 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisInsight(); + +var awsConfig = builder.AddAWSSDKConfig() + .WithProfile("default") + .WithRegion(RegionEndpoint.EUCentral1); + +var localstack = builder.AddLocalStack("localstack", awsConfig: awsConfig, configureContainer: container => +{ + container.Lifetime = ContainerLifetime.Session; + container.DebugLevel = 1; + container.LogLevel = LocalStackLogLevel.Debug; + container.Port = 4566; + container.AdditionalEnvironmentVariables.Add("DEBUG", "1"); +}); + +var awsResources = builder + .AddAWSCloudFormationTemplate("resources", "CloudFormation/courseapp-template.yaml", "courseapp") + .WithReference(awsConfig); + +var apiGateway = builder.AddProject("api-gateway"); + +for (var i = 0; i < 5; i++) +{ + var courseApi = builder.AddProject($"courseapp-api-{i}", launchProfileName: null) + .WithHttpsEndpoint(port: 5213 + i) + .WithReference(redis) + .WithReference(awsResources) + .WaitFor(redis) + .WaitFor(awsResources); + + apiGateway.WaitFor(courseApi); +} + +builder.AddProject("client-wasm") + .WaitFor(apiGateway); + +builder.AddProject("courseapp-fileservice") + .WithReference(awsResources) + .WaitFor(awsResources); + +builder.UseLocalStack(localstack); + +builder.Build().Run(); diff --git a/CourseApp/CourseApp.AppHost/CloudFormation/courseapp-template.yaml b/CourseApp/CourseApp.AppHost/CloudFormation/courseapp-template.yaml new file mode 100755 index 00000000..78587c3d --- /dev/null +++ b/CourseApp/CourseApp.AppHost/CloudFormation/courseapp-template.yaml @@ -0,0 +1,52 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: 'CloudFormation template for CourseApp: SQS queue and S3 bucket' + +Parameters: + BucketName: + Type: String + Description: Name for the S3 bucket + Default: 'courseapp-bucket' + + QueueName: + Type: String + Description: Name for the SQS queue + Default: 'courseapp-queue' + +Resources: + CourseBucket: + Type: AWS::S3::Bucket + Properties: + BucketName: !Ref BucketName + VersioningConfiguration: + Status: Suspended + PublicAccessBlockConfiguration: + BlockPublicAcls: true + BlockPublicPolicy: true + IgnorePublicAcls: true + RestrictPublicBuckets: true + + CourseQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: !Ref QueueName + VisibilityTimeout: 30 + MessageRetentionPeriod: 345600 + DelaySeconds: 0 + ReceiveMessageWaitTimeSeconds: 0 + +Outputs: + S3BucketName: + Description: Name of the S3 bucket + Value: !Ref CourseBucket + + S3BucketArn: + Description: ARN of the S3 bucket + Value: !GetAtt CourseBucket.Arn + + SQSQueueName: + Description: Name of the SQS queue + Value: !GetAtt CourseQueue.QueueName + + SQSQueueArn: + Description: ARN of the SQS queue + Value: !GetAtt CourseQueue.Arn diff --git a/CourseApp/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp/CourseApp.AppHost/CourseApp.AppHost.csproj new file mode 100755 index 00000000..e7390432 --- /dev/null +++ b/CourseApp/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -0,0 +1,32 @@ + + + + + + Exe + net8.0 + enable + enable + c81391d2-28b1-41ef-bc85-6df5de587604 + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/CourseApp/CourseApp.AppHost/Properties/launchSettings.json b/CourseApp/CourseApp.AppHost/Properties/launchSettings.json new file mode 100755 index 00000000..b3abb100 --- /dev/null +++ b/CourseApp/CourseApp.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:17210;http://localhost:15223", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21088", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22166" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15223", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19119", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20071" + } + } + } +} diff --git a/CourseApp/CourseApp.AppHost/appsettings.Development.json b/CourseApp/CourseApp.AppHost/appsettings.Development.json new file mode 100755 index 00000000..ff66ba6b --- /dev/null +++ b/CourseApp/CourseApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp/CourseApp.AppHost/appsettings.json b/CourseApp/CourseApp.AppHost/appsettings.json new file mode 100755 index 00000000..f4485893 --- /dev/null +++ b/CourseApp/CourseApp.AppHost/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + }, + "LocalStack": { + "UseLocalStack": true + } +} diff --git a/CourseApp/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj b/CourseApp/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj new file mode 100755 index 00000000..f40f4e11 --- /dev/null +++ b/CourseApp/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CourseApp/CourseApp.ServiceDefaults/Extensions.cs b/CourseApp/CourseApp.ServiceDefaults/Extensions.cs new file mode 100755 index 00000000..bf34b046 --- /dev/null +++ b/CourseApp/CourseApp.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/README.md b/README.md old mode 100644 new mode 100755 index dcaa5eb7..7d8936f9 --- a/README.md +++ b/README.md @@ -1,128 +1,60 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](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). +# Современные технологии разработки ПО +Проект микросервисного бекенда для генерации данных об учебных курсах с кэшированием и балансировкой нагрузки. + +## Лабораторная работа 1. Кэширование + +- Реализован сервис генерации учебных курсов на основе Bogus +- Реализовано кэширование с помощью `IDistributedCache` и Redis +- Реализовано структурное логирование сервиса генерации +- Настроена оркестрация .NET Aspire + +### Предметная область — Учебный курс + +| # | Характеристика | Тип данных | +|---|----------------|------------| +| 1 | Идентификатор в системе | `int` | +| 2 | Наименование курса | `string` | +| 3 | ФИО преподавателя | `string` | +| 4 | Дата начала | `DateOnly` | +| 5 | Дата окончания | `DateOnly` | +| 6 | Максимальное число студентов | `int` | +| 7 | Текущее число студентов | `int` | +| 8 | Выдача сертификата | `bool` | +| 9 | Стоимость | `decimal` | +| 10 | Рейтинг | `int` | + +## Лабораторная работа 2. Балансировка нагрузки + +- Настроена оркестрация на запуск 5 реплик сервиса генерации +- Реализован API Gateway на основе Ocelot +- Имплементирован алгоритм балансировки Weighted Random + +### Алгоритм Weighted Random + +Каждой реплике сервиса присваивается вероятность выбора (сумма вероятностей равна 1). При поступлении запроса реплика выбирается случайно с учётом назначенных весов. + +## Лабораторная работа 3. Интеграционное тестирование + +- В оркестрацию добавлено объектное хранилище (S3 в эмуляции LocalStack) и брокер сообщений (SQS в эмуляции LocalStack) +- Ресурсы (S3 bucket, SQS queue) объявлены через CloudFormation-шаблон и поднимаются через `AddAWSCloudFormationTemplate` +- Реализован файловый сервис `CourseApp.FileService`, потребляющий сообщения из SQS и сохраняющий курсы в S3 в виде JSON-файлов +- В `CourseApp.Api` добавлен SQS-продюсер: после генерации нового курса сообщение публикуется в очередь +- Реализованы интеграционные тесты на основе `Aspire.Hosting.Testing`, проверяющие сквозной пайплайн всех сервисов + +### Вариант реализации + +| Компонент | Технология | +|-----------|------------| +| Брокер сообщений | AWS SQS (в эмуляции LocalStack) | +| Объектное хранилище | AWS S3 (в эмуляции LocalStack) | +| AWS SDK конфигурация | LocalStack.Client + AWSSDK.SQS / AWSSDK.S3 | + +### Интеграционные тесты + +Проект `CourseApp.AppHost.Tests` поднимает весь `DistributedApplication` через `Aspire.Hosting.Testing` и прогоняет реальные HTTP-запросы по сквозному пайплайну. Один экземпляр приложения шарится между тестами через `IAsyncLifetime`, тесты используют разные `id`, чтобы не конфликтовать по ключам в S3. + +| Тест | Что проверяет | +|------|---------------| +| `Pipeline_PutsGeneratedCourseToS3` | Сквозной happy-path: запрос к API кладёт сериализованный курс в S3 идентичным тому, что вернулся клиенту (`HTTP → CourseService → SQS → SqsConsumerService → S3`) | +| `Pipeline_CacheHitDoesNotDuplicateFile` | Идемпотентность: при cache hit отправка в SQS не происходит повторно — в S3 остаётся ровно один файл `course_{id}.json` | \ No newline at end of file