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..adedb666
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №2 "Кэширование"
+ Вариант №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..15209372
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -1,25 +1,49 @@
-
-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
+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
+ 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..2e3fa898
--- /dev/null
+++ b/CourseApp.Api/CourseApp.Api.csproj
@@ -0,0 +1,18 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
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/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..d83edce7
--- /dev/null
+++ b/CourseApp.Api/Program.cs
@@ -0,0 +1,17 @@
+using CourseApp.Api.Services;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("redis");
+
+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..f2c42007
--- /dev/null
+++ b/CourseApp.Api/Services/CourseService.cs
@@ -0,0 +1,86 @@
+using System.Text.Json;
+using CourseApp.Api.Generators;
+using CourseApp.Api.Models;
+using Microsoft.Extensions.Caching.Distributed;
+
+namespace CourseApp.Api.Services;
+
+///
+/// Сервис учебных курсов с кэшированием в Redis
+///
+/// Распределённый кэш
+/// Конфигурация приложения
+/// Логгер
+public sealed class CourseService(
+ IDistributedCache cache,
+ 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 with id {Id}", id);
+ return cachedCourse;
+ }
+
+ logger.LogInformation("Cache miss for course with id {Id}", id);
+
+ var course = CourseGenerator.Generate(id);
+ logger.LogInformation("Generated course {@Course}", course);
+
+ await TrySetToCache(id, course);
+
+ return course;
+ }
+
+ private async Task TryGetFromCache(int id)
+ {
+ try
+ {
+ var key = CacheKeyPrefix + id;
+ var data = await cache.GetStringAsync(key);
+
+ if (data is null)
+ return null;
+
+ return JsonSerializer.Deserialize(data);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error reading course with id {Id} from cache", id);
+ return null;
+ }
+ }
+
+ private async Task TrySetToCache(int id, Course course)
+ {
+ try
+ {
+ var key = CacheKeyPrefix + id;
+ var data = JsonSerializer.Serialize(course);
+ var options = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = _cacheExpiration
+ };
+ await cache.SetStringAsync(key, data, options);
+
+ logger.LogInformation("Course with id {Id} saved to cache", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error saving course with id {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/CourseApp.AppHost/AppHost.cs b/CourseApp/CourseApp.AppHost/AppHost.cs
new file mode 100755
index 00000000..e25220ea
--- /dev/null
+++ b/CourseApp/CourseApp.AppHost/AppHost.cs
@@ -0,0 +1,21 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var redis = builder.AddRedis("redis")
+ .WithRedisInsight();
+
+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)
+ .WaitFor(redis);
+
+ apiGateway.WaitFor(courseApi);
+}
+
+builder.AddProject("client-wasm")
+ .WaitFor(apiGateway);
+
+builder.Build().Run();
diff --git a/CourseApp/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp/CourseApp.AppHost/CourseApp.AppHost.csproj
new file mode 100755
index 00000000..06c07053
--- /dev/null
+++ b/CourseApp/CourseApp.AppHost/CourseApp.AppHost.csproj
@@ -0,0 +1,24 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ c81391d2-28b1-41ef-bc85-6df5de587604
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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..2185f955
--- /dev/null
+++ b/CourseApp/CourseApp.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
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..2608c03c
--- a/README.md
+++ b/README.md
@@ -1,128 +1,35 @@
-# Современные технологии разработки программного обеспечения
-[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing)
+# Современные технологии разработки ПО
-## Задание
-### Цель
-Реализация проекта микросервисного бекенда.
+Проект микросервисного бекенда для генерации данных об учебных курсах с кэшированием и балансировкой нагрузки.
-### Задачи
-* Реализация межсервисной коммуникации,
-* Изучение работы с брокерами сообщений,
-* Изучение архитектурных паттернов,
-* Изучение работы со средствами оркестрации на примере .NET Aspire,
-* Повторение основ работы с системами контроля версий,
-* Интеграционное тестирование.
+## Лабораторная работа 1. Кэширование
-### Лабораторные работы
-
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов
-
-
-В рамках первой лабораторной работы необходимо:
-* Реализовать сервис генерации контрактов на основе Bogus,
-* Реализовать кеширование при помощи IDistributedCache и Redis,
-* Реализовать структурное логирование сервиса генерации,
-* Настроить оркестрацию Aspire.
-
-
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы
-
-
-В рамках второй лабораторной работы необходимо:
-* Настроить оркестрацию на запуск нескольких реплик сервиса генерации,
-* Реализовать апи гейтвей на основе Ocelot,
-* Имплементировать алгоритм балансировки нагрузки согласно варианту.
+- Реализован сервис генерации учебных курсов на основе Bogus
+- Реализовано кэширование с помощью `IDistributedCache` и Redis
+- Реализовано структурное логирование сервиса генерации
+- Настроена оркестрация .NET Aspire
-
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда
-
+### Предметная область — Учебный курс
-В рамках третьей лабораторной работы необходимо:
-* Добавить в оркестрацию объектное хранилище,
-* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище,
-* Реализовать отправку генерируемых данных в файловый сервис посредством брокера,
-* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе.
+| # | Характеристика | Тип данных |
+|---|----------------|------------|
+| 1 | Идентификатор в системе | `int` |
+| 2 | Наименование курса | `string` |
+| 3 | ФИО преподавателя | `string` |
+| 4 | Дата начала | `DateOnly` |
+| 5 | Дата окончания | `DateOnly` |
+| 6 | Максимальное число студентов | `int` |
+| 7 | Текущее число студентов | `int` |
+| 8 | Выдача сертификата | `bool` |
+| 9 | Стоимость | `decimal` |
+| 10 | Рейтинг | `int` |
-
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud
-
-
-В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы:
-* Клиент - в хостинг через отдельный бакет Object Storage,
-* Сервис генерации - в Cloud Function,
-* Апи гейтвей - в Serverless Integration как API Gateway,
-* Брокер сообщений - в Message Queue,
-* Файловый сервис - в Cloud Function,
-* Объектное хранилище - в отдельный бакет Object Storage,
+## Лабораторная работа 2. Балансировка нагрузки
-
-
+- Настроена оркестрация на запуск 5 реплик сервиса генерации
+- Реализован API Gateway на основе Ocelot
+- Имплементирован алгоритм балансировки Weighted Random
-## Задание. Общая часть
-**Обязательно**:
-* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview).
-* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview).
-* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus).
-* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs).
-* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация.
-
-**Факультативно**:
-* Перенос бекенда на облачную инфраструктуру Yandex Cloud
-
-Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью.
-Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю.
-
-По итогу работы в семестре должна получиться следующая информационная система:
-
-C4 диаграмма
-
-
-
-## Варианты заданий
-Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи.
-
-[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing)
-[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing)
-
-## Схема сдачи
-
-На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests).
-
-Общая схема:
-1. Сделать форк данного репозитория
-2. Выполнить задание
-3. Сделать PR в данный репозиторий
-4. Исправить замечания после code review
-5. Получить approve
-
-## Критерии оценивания
-
-Конкурентный принцип.
-Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки:
-1. Скорость разработки
-2. Качество разработки
-3. Полнота выполнения задания
-
-Быстрее делаете PR - у вас преимущество.
-Быстрее получаете Approve - у вас преимущество.
-Выполните нечто немного выходящее за рамки проекта - у вас преимущество.
-Не укладываетесь в дедлайн - получаете минимально возможный балл.
-
-### Шкала оценивания
-
-- **3 балла** за качество кода, из них:
- - 2 балла - базовая оценка
- - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов:
- - Реализация факультативного функционала
- - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл
-
-## Вопросы и обратная связь по курсу
-
-Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new).
-Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas).
+### Алгоритм Weighted Random
+Каждой реплике сервиса присваивается вероятность выбора (сумма вероятностей равна 1). При поступлении запроса реплика выбирается случайно с учётом назначенных весов.