From 95f76c8a6fe29343c095fb51848acd0b3163bbf8 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sun, 22 Feb 2026 17:24:07 +0400 Subject: [PATCH 01/12] complete lab1 --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 18 +++ CompanyEmployee.AppHost/AppHost.cs | 14 ++ .../CompanyEmployee.AppHost.csproj | 23 ++++ .../Properties/launchSettings.json | 31 +++++ .../appsettings.Development.json | 8 ++ CompanyEmployee.AppHost/appsettings.json | 9 ++ .../CompanyEmployee.Generator.csproj | 19 +++ .../Controller/CompanyEmployeeController.cs | 19 +++ .../Dto/CompanyEmployeeDto.cs | 57 ++++++++ CompanyEmployee.Generator/Program.cs | 57 ++++++++ .../Properties/launchSettings.json | 41 ++++++ .../Service/CompanyEmployeeGenerator.cs | 74 ++++++++++ .../Service/CompanyEmployeeService.cs | 63 +++++++++ .../appsettings.Development.json | 8 ++ CompanyEmployee.Generator/appsettings.json | 13 ++ .../CompanyEmployee.ServiceDefaults.csproj | 22 +++ CompanyEmployee.ServiceDefaults/Extensions.cs | 130 ++++++++++++++++++ 19 files changed, 611 insertions(+), 5 deletions(-) create mode 100644 CompanyEmployee.AppHost/AppHost.cs create mode 100644 CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj create mode 100644 CompanyEmployee.AppHost/Properties/launchSettings.json create mode 100644 CompanyEmployee.AppHost/appsettings.Development.json create mode 100644 CompanyEmployee.AppHost/appsettings.json create mode 100644 CompanyEmployee.Generator/CompanyEmployee.Generator.csproj create mode 100644 CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs create mode 100644 CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs create mode 100644 CompanyEmployee.Generator/Program.cs create mode 100644 CompanyEmployee.Generator/Properties/launchSettings.json create mode 100644 CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs create mode 100644 CompanyEmployee.Generator/Service/CompanyEmployeeService.cs create mode 100644 CompanyEmployee.Generator/appsettings.Development.json create mode 100644 CompanyEmployee.Generator/appsettings.json create mode 100644 CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj create mode 100644 CompanyEmployee.ServiceDefaults/Extensions.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..e86fb27e 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + Вариант №36 "Сотрудник компании" + Выполнена Барышниковым Владиславом 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..5f43a0ad 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7240/company-employee" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..0956a72f 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,6 +5,12 @@ 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}") = "CompanyEmployee.Generator", "CompanyEmployee.Generator\CompanyEmployee.Generator.csproj", "{76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.AppHost", "CompanyEmployee.AppHost\CompanyEmployee.AppHost.csproj", "{11A4C40B-7996-4885-88E1-FA478E8AC6B6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ServiceDefaults", "CompanyEmployee.ServiceDefaults\CompanyEmployee.ServiceDefaults.csproj", "{DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +21,18 @@ Global {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {76AE3AB2-7AF9-4BAA-BE4F-1FDEE3D052AA}.Release|Any CPU.Build.0 = Release|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11A4C40B-7996-4885-88E1-FA478E8AC6B6}.Release|Any CPU.Build.0 = Release|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs new file mode 100644 index 00000000..5988981e --- /dev/null +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -0,0 +1,14 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("cache") + .WithRedisInsight(containerName: "redis-insight"); + +var generator = builder.AddProject("generator") + .WithReference(cache) + .WaitFor(cache); + +var client = builder.AddProject("client") + .WithReference(generator) + .WaitFor(generator); + +builder.Build().Run(); \ No newline at end of file diff --git a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj new file mode 100644 index 00000000..bbe14523 --- /dev/null +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + Exe + net8.0 + enable + enable + 9511602b-1df2-46c9-8aeb-4a3bacf565a2 + + + + + + + + + + + + + diff --git a/CompanyEmployee.AppHost/Properties/launchSettings.json b/CompanyEmployee.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..4fac06bc --- /dev/null +++ b/CompanyEmployee.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17150;http://localhost:15212", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21292", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23155", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22112" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15212", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19225", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18266", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20084" + } + } + } +} diff --git a/CompanyEmployee.AppHost/appsettings.Development.json b/CompanyEmployee.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.AppHost/appsettings.json b/CompanyEmployee.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/CompanyEmployee.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj b/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj new file mode 100644 index 00000000..c77f42f1 --- /dev/null +++ b/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs new file mode 100644 index 00000000..cb3f404c --- /dev/null +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -0,0 +1,19 @@ +using CompanyEmployee.Generator.Dto; +using CompanyEmployee.Generator.Service; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.Generator.Controller; + +[ApiController] +[Route("company-employee")] +public class CompanyEmployeeController( + CompanyEmployeeService service + ) : ControllerBase +{ + [HttpGet] + public async Task> GetById([FromQuery] int id, CancellationToken cancellationToken) + { + var employee = await service.GetByIdAsync(id, cancellationToken); + return Ok(employee); + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs new file mode 100644 index 00000000..bb8fdf0b --- /dev/null +++ b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs @@ -0,0 +1,57 @@ +namespace CompanyEmployee.Generator.Dto; + +/// +/// Информация о сотруднике компании +/// +public class CompanyEmployeeDto +{ + /// + /// Идентификатор сотрудника в системе + /// + public int Id { get; set; } + + /// + /// ФИО + /// + public string FullName { get; set; } + + /// + /// Должность + /// + public string Position { get; set; } + + /// + /// Отдел + /// + public string Department { get; set; } + + /// + /// Дата приема + /// + public DateOnly EmploymentDate { get; set; } + + /// + /// Оклад + /// + public decimal Salary { get; set; } + + /// + /// Электронная почта + /// + public string Email { get; set; } + + /// + /// Номер телефона + /// + public string PhoneNumber { get; set; } + + /// + /// Индикатор увольнения + /// + public bool DismissalFlag { get; set; } + + /// + /// Дата увольнения + /// + public DateOnly? DismissalDate { get; set; } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs new file mode 100644 index 00000000..715f88b2 --- /dev/null +++ b/CompanyEmployee.Generator/Program.cs @@ -0,0 +1,57 @@ +using CompanyEmployee.ServiceDefaults; +using CompanyEmployee.Generator.Service; + + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + policy.SetIsOriginAllowed(origin => + { + try + { + var uri = new Uri(origin); + return uri.Host == "localhost"; + } + catch + { + return false; + } + }) + .WithMethods("GET") + .AllowAnyHeader()); +}); + +builder.AddRedisDistributedCache(connectionName: "cache"); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +var app = builder.Build(); + +app.UseCors(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.UseCors("wasm"); + +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.Generator/Properties/launchSettings.json b/CompanyEmployee.Generator/Properties/launchSettings.json new file mode 100644 index 00000000..ea64f59f --- /dev/null +++ b/CompanyEmployee.Generator/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:6127", + "sslPort": 44325 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7240;http://localhost:5291", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs new file mode 100644 index 00000000..732d614e --- /dev/null +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -0,0 +1,74 @@ +using Bogus; +using Bogus.DataSets; +using CompanyEmployee.Generator.Dto; + +namespace CompanyEmployee.Generator.Service; + +public class CompanyEmployeeGenerator( + ILogger logger + ) +{ + private static readonly string[] _position = ["Developer", "Manager", "Analyst", "QA"]; + + private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; + + private static readonly string[] _malePatronymic = + [ + "Александрович", "Сергеевич", "Иванович", "Дмитриевич", "Владимирович", + "Андреевич", "Михайлович", "Николаевич", "Павлович", "Викторович" + ]; + + private static readonly string[] _femalePatronymic = + [ + "Алексеевна", "Сергеевна", "Ивановна", "Дмитриевна", "Владимировна", + "Андреевна", "Михайловна", "Николаевна", "Павловна", "Викторовна" + ]; + + public CompanyEmployeeDto Generate(int id) + { + var faker = new Faker("ru") + .RuleFor(e => e.Id, _ => id) + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); + + string patronymic; + if (gender == Name.Gender.Male) + { + patronymic = f.PickRandom(_malePatronymic); + } + else + { + patronymic = f.PickRandom(_femalePatronymic); + } + + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} {patronymic}"; + }) + .RuleFor(e => e.Position, f => $"{f.PickRandom(_position)} {f.PickRandom(_grade)}") + .RuleFor(e => e.Department, f => f.Commerce.Department()) + .RuleFor(e => e.EmploymentDate, f => f.Date.PastDateOnly(10)) + .RuleFor(e => e.Salary, (f, e) => + { + var baseSalary = f.Random.Decimal(100, 200); + + for (var i = 0; i < _grade.Length; ++i) + { + if (e.Position.Contains(_grade[i])) + { + baseSalary *= (i + 1); + break; + } + } + + return Math.Round(baseSalary, 2); + }) + .RuleFor(e => e.Email, f => f.Internet.Email()) + .RuleFor(e => e.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(e => e.DismissalFlag, f => f.Finance.Random.Bool(0.5f)) + .RuleFor(e => e.DismissalDate, + (f, e) => f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); + + logger.LogInformation("Generated employee with id {}", id); + return faker.Generate(); + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs new file mode 100644 index 00000000..5f63acc9 --- /dev/null +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -0,0 +1,63 @@ +using System.Text.Json; +using CompanyEmployee.Generator.Dto; +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Generator.Service; + +public class CompanyEmployeeService( + CompanyEmployeeGenerator generator, + IDistributedCache cache, + IConfiguration configuration, + ILogger logger + ) +{ + private static readonly string _companyEmployeeCachePrefix = "company-employee:"; + + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + + public async Task GetByIdAsync(int id, CancellationToken token) + { + var cacheKey = _companyEmployeeCachePrefix + id; + var cachedValue = await cache.GetStringAsync(cacheKey, token); + + CompanyEmployeeDto companyEmployee; + + if (!string.IsNullOrEmpty(cachedValue)) + { + logger.LogInformation("Read from cache, key: {}", cacheKey); + try + { + companyEmployee = JsonSerializer.Deserialize(cachedValue, _jsonOptions); + if (companyEmployee != null) + { + return companyEmployee; + } + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error deserializing cached employee, key: {}", cacheKey); + } + } + + companyEmployee = generator.Generate(id); + + var ttlSeconds = configuration.GetValue("CreditOrderCache:TtlSeconds", 600); + var cacheOpts = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ttlSeconds) + }; + + try + { + await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(companyEmployee, _jsonOptions), cacheOpts, + token); + logger.LogInformation("Write to cache, key: {}", cacheKey); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error in caching companyEmployee, key: {}", cacheKey); + } + + return companyEmployee; + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/appsettings.Development.json b/CompanyEmployee.Generator/appsettings.Development.json new file mode 100644 index 00000000..cd7d0bc9 --- /dev/null +++ b/CompanyEmployee.Generator/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/appsettings.json b/CompanyEmployee.Generator/appsettings.json new file mode 100644 index 00000000..cc8adff1 --- /dev/null +++ b/CompanyEmployee.Generator/appsettings.json @@ -0,0 +1,13 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CreditOrderCache": { + "Enabled": true, + "TtlSeconds": 60 + }, + "AllowedHosts": "*" +} \ No newline at end of file diff --git a/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj new file mode 100644 index 00000000..1214e27d --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/CompanyEmployee.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.ServiceDefaults/Extensions.cs b/CompanyEmployee.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..0c76f9c8 --- /dev/null +++ b/CompanyEmployee.ServiceDefaults/Extensions.cs @@ -0,0 +1,130 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CompanyEmployee.ServiceDefaults; + +// 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; + } +} \ No newline at end of file From 7dadb1fec3c466b1367b996cdbd344cd6f0c334c Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sun, 22 Feb 2026 17:37:41 +0400 Subject: [PATCH 02/12] add summary --- .../Controller/CompanyEmployeeController.cs | 20 ++++++++++++++++++- .../Service/CompanyEmployeeGenerator.cs | 8 ++++++++ .../Service/CompanyEmployeeService.cs | 10 ++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs index cb3f404c..a8499aac 100644 --- a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -4,15 +4,33 @@ namespace CompanyEmployee.Generator.Controller; +/// +/// Контроллер для получения сотрудника компании по id +/// [ApiController] [Route("company-employee")] public class CompanyEmployeeController( - CompanyEmployeeService service + CompanyEmployeeService service, + Logger logger ) : ControllerBase { + /// + /// Метод для получения сотрудника компании по id + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании + /// Успешное получение сотрудника + /// Некорректный id [HttpGet] public async Task> GetById([FromQuery] int id, CancellationToken cancellationToken) { + if (id <= 0) + { + return BadRequest("Id must be greater or equal than 0"); + } + logger.LogInformation($"HTTP GET /company-employee, id: {id}", id); + var employee = await service.GetByIdAsync(id, cancellationToken); return Ok(employee); } diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 732d614e..76d10a5f 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -4,6 +4,9 @@ namespace CompanyEmployee.Generator.Service; +/// +/// Генератор сотрудника по идентификатору +/// public class CompanyEmployeeGenerator( ILogger logger ) @@ -24,6 +27,11 @@ ILogger logger "Андреевна", "Михайловна", "Николаевна", "Павловна", "Викторовна" ]; + /// + /// Метод для генерации сотрудника по идентификатору + /// + /// Идентификатор сотрудника + /// DTO сотрудника компании public CompanyEmployeeDto Generate(int id) { var faker = new Faker("ru") diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 5f63acc9..ec159d8b 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -4,6 +4,9 @@ namespace CompanyEmployee.Generator.Service; +/// +/// Сервис получения сотрудника компании +/// public class CompanyEmployeeService( CompanyEmployeeGenerator generator, IDistributedCache cache, @@ -15,6 +18,13 @@ ILogger logger private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + /// + /// Метод получения сотрудника компании по идентификатору + /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании public async Task GetByIdAsync(int id, CancellationToken token) { var cacheKey = _companyEmployeeCachePrefix + id; From 2dcef8c819fcabc4e79117919b5767171551dc26 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sun, 22 Feb 2026 18:52:57 +0400 Subject: [PATCH 03/12] change cache ttl --- CompanyEmployee.Generator/Service/CompanyEmployeeService.cs | 2 +- CompanyEmployee.Generator/appsettings.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index ec159d8b..5f08c060 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -51,7 +51,7 @@ public async Task GetByIdAsync(int id, CancellationToken tok companyEmployee = generator.Generate(id); - var ttlSeconds = configuration.GetValue("CreditOrderCache:TtlSeconds", 600); + var ttlSeconds = configuration.GetValue("CompanyEmployeeCache:TtlSeconds", 600); var cacheOpts = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ttlSeconds) diff --git a/CompanyEmployee.Generator/appsettings.json b/CompanyEmployee.Generator/appsettings.json index cc8adff1..e6d8e7b2 100644 --- a/CompanyEmployee.Generator/appsettings.json +++ b/CompanyEmployee.Generator/appsettings.json @@ -5,9 +5,9 @@ "Microsoft.AspNetCore": "Warning" } }, - "CreditOrderCache": { + "CompanyEmployeeCache": { "Enabled": true, - "TtlSeconds": 60 + "TtlSeconds": 600 }, "AllowedHosts": "*" } \ No newline at end of file From 3131e49c85d070d43e95d671081972489d205798 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Tue, 24 Feb 2026 18:06:08 +0400 Subject: [PATCH 04/12] fix lab --- .../Controller/CompanyEmployeeController.cs | 10 +++--- .../Dto/CompanyEmployeeDto.cs | 20 ++++++------ CompanyEmployee.Generator/Program.cs | 4 +-- .../Service/CompanyEmployeeGenerator.cs | 32 ++----------------- .../Service/CompanyEmployeeService.cs | 11 ++----- .../Service/ICompanyEmployeeGenerator.cs | 17 ++++++++++ .../Service/ICompanyEmployeeService.cs | 18 +++++++++++ 7 files changed, 58 insertions(+), 54 deletions(-) create mode 100644 CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs create mode 100644 CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs index a8499aac..4ef2d0b3 100644 --- a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -10,8 +10,8 @@ namespace CompanyEmployee.Generator.Controller; [ApiController] [Route("company-employee")] public class CompanyEmployeeController( - CompanyEmployeeService service, - Logger logger + ICompanyEmployeeService service, + ILogger logger ) : ControllerBase { /// @@ -23,13 +23,15 @@ Logger logger /// Успешное получение сотрудника /// Некорректный id [HttpGet] + [ProducesResponseType(typeof(CompanyEmployeeDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] public async Task> GetById([FromQuery] int id, CancellationToken cancellationToken) { - if (id <= 0) + if (id < 0) { return BadRequest("Id must be greater or equal than 0"); } - logger.LogInformation($"HTTP GET /company-employee, id: {id}", id); + logger.LogInformation("HTTP GET /company-employee, id: {id}", id); var employee = await service.GetByIdAsync(id, cancellationToken); return Ok(employee); diff --git a/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs index bb8fdf0b..51192f96 100644 --- a/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs +++ b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs @@ -8,50 +8,50 @@ public class CompanyEmployeeDto /// /// Идентификатор сотрудника в системе /// - public int Id { get; set; } + public required int Id { get; init; } /// /// ФИО /// - public string FullName { get; set; } + public required string FullName { get; init; } /// /// Должность /// - public string Position { get; set; } + public required string Position { get; init; } /// /// Отдел /// - public string Department { get; set; } + public required string Department { get; init; } /// /// Дата приема /// - public DateOnly EmploymentDate { get; set; } + public required DateOnly EmploymentDate { get; init; } /// /// Оклад /// - public decimal Salary { get; set; } + public required decimal Salary { get; init; } /// /// Электронная почта /// - public string Email { get; set; } + public required string Email { get; init; } /// /// Номер телефона /// - public string PhoneNumber { get; set; } + public required string PhoneNumber { get; init; } /// /// Индикатор увольнения /// - public bool DismissalFlag { get; set; } + public required bool DismissalFlag { get; init; } /// /// Дата увольнения /// - public DateOnly? DismissalDate { get; set; } + public DateOnly? DismissalDate { get; init; } } \ No newline at end of file diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs index 715f88b2..cec0ba1d 100644 --- a/CompanyEmployee.Generator/Program.cs +++ b/CompanyEmployee.Generator/Program.cs @@ -31,8 +31,8 @@ builder.AddRedisDistributedCache(connectionName: "cache"); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); var app = builder.Build(); diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 76d10a5f..84a65a0e 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -9,29 +9,12 @@ namespace CompanyEmployee.Generator.Service; /// public class CompanyEmployeeGenerator( ILogger logger - ) + ) : ICompanyEmployeeGenerator { private static readonly string[] _position = ["Developer", "Manager", "Analyst", "QA"]; private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; - private static readonly string[] _malePatronymic = - [ - "Александрович", "Сергеевич", "Иванович", "Дмитриевич", "Владимирович", - "Андреевич", "Михайлович", "Николаевич", "Павлович", "Викторович" - ]; - - private static readonly string[] _femalePatronymic = - [ - "Алексеевна", "Сергеевна", "Ивановна", "Дмитриевна", "Владимировна", - "Андреевна", "Михайловна", "Николаевна", "Павловна", "Викторовна" - ]; - - /// - /// Метод для генерации сотрудника по идентификатору - /// - /// Идентификатор сотрудника - /// DTO сотрудника компании public CompanyEmployeeDto Generate(int id) { var faker = new Faker("ru") @@ -40,17 +23,8 @@ public CompanyEmployeeDto Generate(int id) { var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); - string patronymic; - if (gender == Name.Gender.Male) - { - patronymic = f.PickRandom(_malePatronymic); - } - else - { - patronymic = f.PickRandom(_femalePatronymic); - } - - return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} {patronymic}"; + return $"{f.Name.LastName(gender)} {f.Name.FirstName(gender)} " + + $"{f.Name.FirstName(gender)}{(gender == Name.Gender.Male ? "еевич" : "еевна")}"; }) .RuleFor(e => e.Position, f => $"{f.PickRandom(_position)} {f.PickRandom(_grade)}") .RuleFor(e => e.Department, f => f.Commerce.Department()) diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 5f08c060..3548ef0b 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -8,23 +8,16 @@ namespace CompanyEmployee.Generator.Service; /// Сервис получения сотрудника компании /// public class CompanyEmployeeService( - CompanyEmployeeGenerator generator, + ICompanyEmployeeGenerator generator, IDistributedCache cache, IConfiguration configuration, ILogger logger - ) + ) : ICompanyEmployeeService { private static readonly string _companyEmployeeCachePrefix = "company-employee:"; private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); - /// - /// Метод получения сотрудника компании по идентификатору - /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш - /// - /// Идентификатор сотрудника - /// Токен отмены запроса - /// DTO сотрудника компании public async Task GetByIdAsync(int id, CancellationToken token) { var cacheKey = _companyEmployeeCachePrefix + id; diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs new file mode 100644 index 00000000..f28bb183 --- /dev/null +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs @@ -0,0 +1,17 @@ +using CompanyEmployee.Generator.Dto; + +namespace CompanyEmployee.Generator.Service; + +/// +/// Интерфейс генератора сотрудника по идентификатору +/// +public interface ICompanyEmployeeGenerator +{ + /// + /// Метод для генерации сотрудника по идентификатору + /// + /// Идентификатор сотрудника + /// DTO сотрудника компании + public CompanyEmployeeDto Generate(int id); + +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs new file mode 100644 index 00000000..339a6e85 --- /dev/null +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs @@ -0,0 +1,18 @@ +using CompanyEmployee.Generator.Dto; + +namespace CompanyEmployee.Generator.Service; + +/// +/// Интерфейс сервиса получения сотрудника компании +/// +public interface ICompanyEmployeeService +{ + /// + /// Метод получения сотрудника компании по идентификатору + /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании + public Task GetByIdAsync(int id, CancellationToken token); +} \ No newline at end of file From 95abf548d4b673bc3639a5c4b9d89af61a92617a Mon Sep 17 00:00:00 2001 From: dedrowe Date: Tue, 24 Feb 2026 20:01:40 +0400 Subject: [PATCH 05/12] fix lab --- CompanyEmployee.Generator/Program.cs | 2 +- .../Service/CompanyEmployeeGenerator.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs index cec0ba1d..aa5e3685 100644 --- a/CompanyEmployee.Generator/Program.cs +++ b/CompanyEmployee.Generator/Program.cs @@ -12,7 +12,7 @@ builder.Services.AddCors(options => { - options.AddDefaultPolicy(policy => + options.AddPolicy("wasm", policy => policy.SetIsOriginAllowed(origin => { try diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 84a65a0e..de5159b5 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -46,9 +46,9 @@ public CompanyEmployeeDto Generate(int id) }) .RuleFor(e => e.Email, f => f.Internet.Email()) .RuleFor(e => e.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) - .RuleFor(e => e.DismissalFlag, f => f.Finance.Random.Bool(0.5f)) - .RuleFor(e => e.DismissalDate, - (f, e) => f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); + .RuleFor(e => e.DismissalFlag, f => f.Random.Bool(0.5f)) + .RuleFor(e => e.DismissalDate, (f, e) => !e.DismissalFlag ? null : + f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); logger.LogInformation("Generated employee with id {}", id); return faker.Generate(); From 62e8ecbf213cf536ae53a51843fc6c613c5adb5c Mon Sep 17 00:00:00 2001 From: dedrowe Date: Thu, 26 Feb 2026 13:10:40 +0400 Subject: [PATCH 06/12] fix lab --- .../Controller/CompanyEmployeeController.cs | 4 +++- .../Service/CompanyEmployeeGenerator.cs | 7 ++++--- .../Service/CompanyEmployeeService.cs | 18 +++++++++++------- .../Service/ICompanyEmployeeGenerator.cs | 4 ++-- .../Service/ICompanyEmployeeService.cs | 4 ++-- 5 files changed, 22 insertions(+), 15 deletions(-) diff --git a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs index 4ef2d0b3..1cf0bee3 100644 --- a/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -7,6 +7,8 @@ namespace CompanyEmployee.Generator.Controller; /// /// Контроллер для получения сотрудника компании по id /// +/// Сервис получения сотрудника компании +/// Логгер [ApiController] [Route("company-employee")] public class CompanyEmployeeController( @@ -31,7 +33,7 @@ public async Task> GetById([FromQuery] int id, { return BadRequest("Id must be greater or equal than 0"); } - logger.LogInformation("HTTP GET /company-employee, id: {id}", id); + logger.LogInformation("HTTP GET /company-employee, id: {employeeId}", id); var employee = await service.GetByIdAsync(id, cancellationToken); return Ok(employee); diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index de5159b5..26d8fa4c 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -7,6 +7,7 @@ namespace CompanyEmployee.Generator.Service; /// /// Генератор сотрудника по идентификатору /// +/// Логгер public class CompanyEmployeeGenerator( ILogger logger ) : ICompanyEmployeeGenerator @@ -15,10 +16,10 @@ ILogger logger private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; - public CompanyEmployeeDto Generate(int id) + public CompanyEmployeeDto Generate(int employeeId) { var faker = new Faker("ru") - .RuleFor(e => e.Id, _ => id) + .RuleFor(e => e.Id, _ => employeeId) .RuleFor(e => e.FullName, f => { var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); @@ -50,7 +51,7 @@ public CompanyEmployeeDto Generate(int id) .RuleFor(e => e.DismissalDate, (f, e) => !e.DismissalFlag ? null : f.Date.BetweenDateOnly(e.EmploymentDate, DateOnly.FromDateTime(DateTime.UtcNow))); - logger.LogInformation("Generated employee with id {}", id); + logger.LogInformation("Generated employee with id {employeeId}", employeeId); return faker.Generate(); } } \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 3548ef0b..22407a26 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -7,6 +7,10 @@ namespace CompanyEmployee.Generator.Service; /// /// Сервис получения сотрудника компании /// +/// Генератор сотрудника по идентификатору +/// Сервис кэширования +/// Конфигурация приложения +/// Логгер public class CompanyEmployeeService( ICompanyEmployeeGenerator generator, IDistributedCache cache, @@ -18,16 +22,16 @@ ILogger logger private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); - public async Task GetByIdAsync(int id, CancellationToken token) + public async Task GetByIdAsync(int employeeId, CancellationToken token) { - var cacheKey = _companyEmployeeCachePrefix + id; + var cacheKey = _companyEmployeeCachePrefix + employeeId; var cachedValue = await cache.GetStringAsync(cacheKey, token); CompanyEmployeeDto companyEmployee; if (!string.IsNullOrEmpty(cachedValue)) { - logger.LogInformation("Read from cache, key: {}", cacheKey); + logger.LogInformation("Read from cache, key: {cacheKey}", cacheKey); try { companyEmployee = JsonSerializer.Deserialize(cachedValue, _jsonOptions); @@ -38,11 +42,11 @@ public async Task GetByIdAsync(int id, CancellationToken tok } catch (Exception ex) { - logger.LogWarning(ex, "Error deserializing cached employee, key: {}", cacheKey); + logger.LogWarning(ex, "Error deserializing cached employee, key: {cacheKey}", cacheKey); } } - companyEmployee = generator.Generate(id); + companyEmployee = generator.Generate(employeeId); var ttlSeconds = configuration.GetValue("CompanyEmployeeCache:TtlSeconds", 600); var cacheOpts = new DistributedCacheEntryOptions @@ -54,11 +58,11 @@ public async Task GetByIdAsync(int id, CancellationToken tok { await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(companyEmployee, _jsonOptions), cacheOpts, token); - logger.LogInformation("Write to cache, key: {}", cacheKey); + logger.LogInformation("Write to cache, key: {cacheKey}", cacheKey); } catch (Exception ex) { - logger.LogWarning(ex, "Error in caching companyEmployee, key: {}", cacheKey); + logger.LogWarning(ex, "Error in caching companyEmployee, key: {cacheKey}", cacheKey); } return companyEmployee; diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs index f28bb183..b2332f3e 100644 --- a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs @@ -10,8 +10,8 @@ public interface ICompanyEmployeeGenerator /// /// Метод для генерации сотрудника по идентификатору /// - /// Идентификатор сотрудника + /// Идентификатор сотрудника /// DTO сотрудника компании - public CompanyEmployeeDto Generate(int id); + public CompanyEmployeeDto Generate(int employeeId); } \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs index 339a6e85..e165687e 100644 --- a/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/ICompanyEmployeeService.cs @@ -11,8 +11,8 @@ public interface ICompanyEmployeeService /// Метод получения сотрудника компании по идентификатору /// Сначала пытается найти сотрудника в кэше, если не находит, то генерирует нового и записывает его в кэш /// - /// Идентификатор сотрудника + /// Идентификатор сотрудника /// Токен отмены запроса /// DTO сотрудника компании - public Task GetByIdAsync(int id, CancellationToken token); + public Task GetByIdAsync(int employeeId, CancellationToken token); } \ No newline at end of file From 7d119fedf19776cd520889d25537b80106e256b0 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Tue, 10 Mar 2026 08:24:24 +0400 Subject: [PATCH 07/12] complete lab2 --- Client.Wasm/Components/StudentCard.razor | 4 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 6 +++ .../CompanyEmployee.ApiGateway.csproj | 17 ++++++++ CompanyEmployee.ApiGateway/Program.cs | 38 ++++++++++++++++ .../Properties/launchSettings.json | 38 ++++++++++++++++ .../QueryBasedLoadBalancer.cs | 43 +++++++++++++++++++ .../appsettings.Development.json | 8 ++++ CompanyEmployee.ApiGateway/appsettings.json | 9 ++++ .../ocelotSettings.json | 18 ++++++++ CompanyEmployee.AppHost/AppHost.cs | 22 +++++++--- .../CompanyEmployee.AppHost.csproj | 1 + CompanyEmployee.Generator/Program.cs | 27 ------------ 13 files changed, 198 insertions(+), 35 deletions(-) create mode 100644 CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj create mode 100644 CompanyEmployee.ApiGateway/Program.cs create mode 100644 CompanyEmployee.ApiGateway/Properties/launchSettings.json create mode 100644 CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs create mode 100644 CompanyEmployee.ApiGateway/appsettings.Development.json create mode 100644 CompanyEmployee.ApiGateway/appsettings.json create mode 100644 CompanyEmployee.ApiGateway/ocelotSettings.json diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index e86fb27e..2c003dae 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,8 +4,8 @@ - Номер №1 "Кэширование" - Вариант №36 "Сотрудник компании" + Номер №2 "Балансировка нагрузки" + Вариант №36 "Query based" Выполнена Барышниковым Владиславом 6513 Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 5f43a0ad..62e100de 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7240/company-employee" + "BaseAddress": "https://localhost:7200/company-employee" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index 0956a72f..faaebec7 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.AppHost", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ServiceDefaults", "CompanyEmployee.ServiceDefaults\CompanyEmployee.ServiceDefaults.csproj", "{DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ApiGateway", "CompanyEmployee.ApiGateway\CompanyEmployee.ApiGateway.csproj", "{00432BCA-E982-451B-9D3F-648FE20FF285}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,6 +35,10 @@ Global {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Debug|Any CPU.Build.0 = Debug|Any CPU {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Release|Any CPU.ActiveCfg = Release|Any CPU {DF70F3CE-6CD9-4334-AB24-0A2BBBD081E8}.Release|Any CPU.Build.0 = Release|Any CPU + {00432BCA-E982-451B-9D3F-648FE20FF285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {00432BCA-E982-451B-9D3F-648FE20FF285}.Debug|Any CPU.Build.0 = Debug|Any CPU + {00432BCA-E982-451B-9D3F-648FE20FF285}.Release|Any CPU.ActiveCfg = Release|Any CPU + {00432BCA-E982-451B-9D3F-648FE20FF285}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj b/CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj new file mode 100644 index 00000000..cdaba523 --- /dev/null +++ b/CompanyEmployee.ApiGateway/CompanyEmployee.ApiGateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/CompanyEmployee.ApiGateway/Program.cs b/CompanyEmployee.ApiGateway/Program.cs new file mode 100644 index 00000000..52e38398 --- /dev/null +++ b/CompanyEmployee.ApiGateway/Program.cs @@ -0,0 +1,38 @@ +using CompanyEmployee.ApiGateway; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddCors(options => +{ + options.AddPolicy("wasm", policy => + policy.SetIsOriginAllowed(origin => + { + try + { + var uri = new Uri(origin); + return uri.Host == "localhost"; + } + catch + { + return false; + } + }) + .WithMethods("GET") + .AllowAnyHeader()); +}); + +builder.Configuration.AddJsonFile("ocelotSettings.json", optional: false, reloadOnChange: true); + +builder.Services.AddOcelot(builder.Configuration).AddCustomLoadBalancer((serviceProvider, _, discoveryProvider) => + new QueryBasedLoadBalancer(discoveryProvider.GetAsync, + serviceProvider.GetRequiredService>())); + +var app = builder.Build(); + +app.UseCors("wasm"); + +await app.UseOcelot(); + +await app.RunAsync(); \ No newline at end of file diff --git a/CompanyEmployee.ApiGateway/Properties/launchSettings.json b/CompanyEmployee.ApiGateway/Properties/launchSettings.json new file mode 100644 index 00000000..f759638c --- /dev/null +++ b/CompanyEmployee.ApiGateway/Properties/launchSettings.json @@ -0,0 +1,38 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:23345", + "sslPort": 44320 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5080", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7236;http://localhost:5080", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs b/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs new file mode 100644 index 00000000..8b1c9d24 --- /dev/null +++ b/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs @@ -0,0 +1,43 @@ +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace CompanyEmployee.ApiGateway; + +public class QueryBasedLoadBalancer(Func>> services, ILogger logger) + : ILoadBalancer +{ + + public string Type => nameof(QueryBasedLoadBalancer); + + public async Task> LeaseAsync(HttpContext context) + { + var availableServices = await services.Invoke(); + if (availableServices.Count == 0) + { + logger.LogError("No services available"); + return new ErrorResponse( + new UnableToFindDownstreamRouteError(context.Request.Path.Value, context.Request.Method)); + } + + var idStr = context.Request.Query["id"].FirstOrDefault("error"); + if (!int.TryParse(idStr, out var index)) + { + logger.LogWarning($"Could not parse id: {idStr}, random replica will be selected", idStr); + index = Random.Shared.Next(availableServices.Count); + } + + index %= availableServices.Count; + if (index < 0) + { + index += availableServices.Count; + } + + logger.LogInformation($"Using replica with index: {index}", index); + + return new OkResponse(availableServices[index].HostAndPort); + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} \ No newline at end of file diff --git a/CompanyEmployee.ApiGateway/appsettings.Development.json b/CompanyEmployee.ApiGateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.ApiGateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.ApiGateway/appsettings.json b/CompanyEmployee.ApiGateway/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/CompanyEmployee.ApiGateway/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CompanyEmployee.ApiGateway/ocelotSettings.json b/CompanyEmployee.ApiGateway/ocelotSettings.json new file mode 100644 index 00000000..e8bbd02b --- /dev/null +++ b/CompanyEmployee.ApiGateway/ocelotSettings.json @@ -0,0 +1,18 @@ +{ + "Routes": [ + { + "DownstreamPathTemplate": "/company-employee", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { "Host": "localhost", "Port": 7301 }, + { "Host": "localhost", "Port": 7302 }, + { "Host": "localhost", "Port": 7303 } + ], + "UpstreamPathTemplate": "/company-employee", + "UpstreamHttpMethod": [ "GET" ], + "LoadBalancerOptions": { + "Type": "QueryBasedLoadBalancer" + } + } + ] +} \ No newline at end of file diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs index 5988981e..ee0ac0bb 100644 --- a/CompanyEmployee.AppHost/AppHost.cs +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -3,12 +3,24 @@ var cache = builder.AddRedis("cache") .WithRedisInsight(containerName: "redis-insight"); -var generator = builder.AddProject("generator") - .WithReference(cache) - .WaitFor(cache); +var gateway = builder.AddProject("apiGateway") + .WithEndpoint("https", e => e.Port = 7200) + .WithExternalHttpEndpoints(); + +const int startGeneratorPort = 7301; +for (var i = 0; i < 3; ++i) +{ + var port = startGeneratorPort + i; + var generator = builder.AddProject($"generator-{i}") + .WithEndpoint("https", e => e.Port = port) + .WithReference(cache) + .WaitFor(cache); + + gateway.WaitFor(generator); +} var client = builder.AddProject("client") - .WithReference(generator) - .WaitFor(generator); + .WithReference(gateway) + .WaitFor(gateway); builder.Build().Run(); \ No newline at end of file diff --git a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj index bbe14523..4758735f 100644 --- a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -17,6 +17,7 @@ + diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs index aa5e3685..a41c1deb 100644 --- a/CompanyEmployee.Generator/Program.cs +++ b/CompanyEmployee.Generator/Program.cs @@ -10,25 +10,6 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddCors(options => -{ - options.AddPolicy("wasm", policy => - policy.SetIsOriginAllowed(origin => - { - try - { - var uri = new Uri(origin); - return uri.Host == "localhost"; - } - catch - { - return false; - } - }) - .WithMethods("GET") - .AllowAnyHeader()); -}); - builder.AddRedisDistributedCache(connectionName: "cache"); builder.Services.AddSingleton(); @@ -36,8 +17,6 @@ var app = builder.Build(); -app.UseCors(); - app.MapDefaultEndpoints(); if (app.Environment.IsDevelopment()) @@ -46,12 +25,6 @@ app.UseSwaggerUI(); } -app.UseHttpsRedirection(); - -app.UseAuthorization(); - -app.UseCors("wasm"); - app.MapControllers(); app.Run(); \ No newline at end of file From 9175eea21caa5bb24299a7b7faccca3655c4357f Mon Sep 17 00:00:00 2001 From: dedrowe Date: Wed, 11 Mar 2026 05:39:36 +0400 Subject: [PATCH 08/12] add summary --- .../QueryBasedLoadBalancer.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs b/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs index 8b1c9d24..808538c3 100644 --- a/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs +++ b/CompanyEmployee.ApiGateway/QueryBasedLoadBalancer.cs @@ -5,12 +5,27 @@ namespace CompanyEmployee.ApiGateway; +/// +/// Класс для балансировкик нагрузки с использованием параметра запроса. +/// +/// Функция, возвращающая список downstream-сервисов +/// Логгер public class QueryBasedLoadBalancer(Func>> services, ILogger logger) : ILoadBalancer { public string Type => nameof(QueryBasedLoadBalancer); + /// + /// Метод для выбора downstream-сервиса на основании параметра запроса. + /// Для выбора используется id из запроса. От него вычисляется остаток от деления на количество downstream-сервисов. + /// После этого выбирается реплика с соответствующим номером. + /// Если из запроса не удалось прочитать id, то используется случайный downstream-сервис. + /// + /// Контекст http-запроса + /// OkResponse с адресос выбранного сервиса, если получилось выбрать downstream-сервис, или + /// ErrorResponse, если определить downstream-сервис не удалось + /// public async Task> LeaseAsync(HttpContext context) { var availableServices = await services.Invoke(); @@ -39,5 +54,10 @@ public async Task> LeaseAsync(HttpContext context) return new OkResponse(availableServices[index].HostAndPort); } + /// + /// Метод предназначен для уведомления о завершении запроса к downstream-сервису. + /// В query based балансировке не используется. + /// + /// Адрес downstream-сервиса public void Release(ServiceHostAndPort hostAndPort) { } } \ No newline at end of file From a2d5321d594b16dbb85e026f56a4e94c16a66aab Mon Sep 17 00:00:00 2001 From: dedrowe Date: Wed, 11 Mar 2026 05:39:58 +0400 Subject: [PATCH 09/12] increase replica count --- CompanyEmployee.ApiGateway/ocelotSettings.json | 4 +++- CompanyEmployee.AppHost/AppHost.cs | 5 ++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CompanyEmployee.ApiGateway/ocelotSettings.json b/CompanyEmployee.ApiGateway/ocelotSettings.json index e8bbd02b..316473ec 100644 --- a/CompanyEmployee.ApiGateway/ocelotSettings.json +++ b/CompanyEmployee.ApiGateway/ocelotSettings.json @@ -6,7 +6,9 @@ "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 7301 }, { "Host": "localhost", "Port": 7302 }, - { "Host": "localhost", "Port": 7303 } + { "Host": "localhost", "Port": 7303 }, + { "Host": "localhost", "Port": 7304 }, + { "Host": "localhost", "Port": 7305 } ], "UpstreamPathTemplate": "/company-employee", "UpstreamHttpMethod": [ "GET" ], diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs index ee0ac0bb..7f8f4366 100644 --- a/CompanyEmployee.AppHost/AppHost.cs +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -8,11 +8,10 @@ .WithExternalHttpEndpoints(); const int startGeneratorPort = 7301; -for (var i = 0; i < 3; ++i) +for (var i = 0; i < 5; ++i) { - var port = startGeneratorPort + i; var generator = builder.AddProject($"generator-{i}") - .WithEndpoint("https", e => e.Port = port) + .WithEndpoint("https", e => e.Port = startGeneratorPort + i) .WithReference(cache) .WaitFor(cache); From 1ee4369bc59e7cc25874b86ef9d2bc3a56aed8fe Mon Sep 17 00:00:00 2001 From: dedrowe Date: Sat, 25 Apr 2026 23:17:43 +0400 Subject: [PATCH 10/12] complete lab3 --- Client.Wasm/Components/StudentCard.razor | 4 +- CloudDevelopment.sln | 12 ++ CompanyEmployee.AppHost/AppHost.cs | 45 +++++- .../CompanyEmployee.AppHost.csproj | 9 ++ CompanyEmployee.AppHost/appsettings.json | 3 + .../CompanyEmployee.EventSink.csproj | 21 +++ .../Controller/S3StorageController.cs | 68 +++++++++ .../Controller/SnsSubscriberController.cs | 68 +++++++++ .../Messaging/SnsSubscriptionService.cs | 50 +++++++ CompanyEmployee.EventSink/Program.cs | 41 ++++++ .../Properties/launchSettings.json | 41 ++++++ CompanyEmployee.EventSink/S3/IS3Service.cs | 33 +++++ .../S3/S3MinioService.cs | 131 +++++++++++++++++ .../appsettings.Development.json | 8 + CompanyEmployee.EventSink/appsettings.json | 9 ++ .../CompanyEmployee.Generator.csproj | 3 + CompanyEmployee.Generator/Program.cs | 9 +- .../Service/CompanyEmployeeGenerator.cs | 1 + .../Service/CompanyEmployeeService.cs | 6 + .../CompanyEmployee.Tests.csproj | 36 +++++ CompanyEmployee.Tests/IntegrationTests.cs | 139 ++++++++++++++++++ 21 files changed, 732 insertions(+), 5 deletions(-) create mode 100644 CompanyEmployee.EventSink/CompanyEmployee.EventSink.csproj create mode 100644 CompanyEmployee.EventSink/Controller/S3StorageController.cs create mode 100644 CompanyEmployee.EventSink/Controller/SnsSubscriberController.cs create mode 100644 CompanyEmployee.EventSink/Messaging/SnsSubscriptionService.cs create mode 100644 CompanyEmployee.EventSink/Program.cs create mode 100644 CompanyEmployee.EventSink/Properties/launchSettings.json create mode 100644 CompanyEmployee.EventSink/S3/IS3Service.cs create mode 100644 CompanyEmployee.EventSink/S3/S3MinioService.cs create mode 100644 CompanyEmployee.EventSink/appsettings.Development.json create mode 100644 CompanyEmployee.EventSink/appsettings.json create mode 100644 CompanyEmployee.Tests/CompanyEmployee.Tests.csproj create mode 100644 CompanyEmployee.Tests/IntegrationTests.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 2c003dae..9c90290f 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,8 +4,8 @@ - Номер №2 "Балансировка нагрузки" - Вариант №36 "Query based" + Номер №3 "Интеграционное тестирование" + Вариант №36 "SNS, Minio" Выполнена Барышниковым Владиславом 6513 Ссылка на форк diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index faaebec7..d133c877 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -13,6 +13,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ServiceDefa EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.ApiGateway", "CompanyEmployee.ApiGateway\CompanyEmployee.ApiGateway.csproj", "{00432BCA-E982-451B-9D3F-648FE20FF285}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.EventSink", "CompanyEmployee.EventSink\CompanyEmployee.EventSink.csproj", "{6EF5D762-90CB-48CA-8D24-1AC90560660F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployee.Tests", "CompanyEmployee.Tests\CompanyEmployee.Tests.csproj", "{28BC6A02-0734-45B8-89E9-EE44E9927921}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -39,6 +43,14 @@ Global {00432BCA-E982-451B-9D3F-648FE20FF285}.Debug|Any CPU.Build.0 = Debug|Any CPU {00432BCA-E982-451B-9D3F-648FE20FF285}.Release|Any CPU.ActiveCfg = Release|Any CPU {00432BCA-E982-451B-9D3F-648FE20FF285}.Release|Any CPU.Build.0 = Release|Any CPU + {6EF5D762-90CB-48CA-8D24-1AC90560660F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6EF5D762-90CB-48CA-8D24-1AC90560660F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6EF5D762-90CB-48CA-8D24-1AC90560660F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6EF5D762-90CB-48CA-8D24-1AC90560660F}.Release|Any CPU.Build.0 = Release|Any CPU + {28BC6A02-0734-45B8-89E9-EE44E9927921}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28BC6A02-0734-45B8-89E9-EE44E9927921}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28BC6A02-0734-45B8-89E9-EE44E9927921}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28BC6A02-0734-45B8-89E9-EE44E9927921}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployee.AppHost/AppHost.cs b/CompanyEmployee.AppHost/AppHost.cs index 7f8f4366..7856cbb3 100644 --- a/CompanyEmployee.AppHost/AppHost.cs +++ b/CompanyEmployee.AppHost/AppHost.cs @@ -1,25 +1,66 @@ +using Amazon; +using Aspire.Hosting.LocalStack.Container; + var builder = DistributedApplication.CreateBuilder(args); var cache = builder.AddRedis("cache") .WithRedisInsight(containerName: "redis-insight"); -var gateway = builder.AddProject("apiGateway") +var gateway = builder.AddProject("api-gateway") .WithEndpoint("https", e => e.Port = 7200) .WithExternalHttpEndpoints(); +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"); + container.AdditionalEnvironmentVariables + .Add("SNS_CERT_URL_HOST", "sns.eu-central-1.amazonaws.com"); + }); + +var awsResources = builder + .AddAWSCloudFormationTemplate("resources", "CloudFormation/company-employee-template-sns.yaml", "company-employee") + .WithReference(awsConfig); + const int startGeneratorPort = 7301; for (var i = 0; i < 5; ++i) { var generator = builder.AddProject($"generator-{i}") .WithEndpoint("https", e => e.Port = startGeneratorPort + i) .WithReference(cache) - .WaitFor(cache); + .WithReference(awsResources) + .WithEnvironment("Settings__MessageBroker", "SNS") + .WaitFor(cache) + .WaitFor(awsResources); gateway.WaitFor(generator); } +var minio = builder.AddMinioContainer("minio"); + +var eventSink = builder.AddProject("event-sink") + .WithReference(awsResources) + .WithEnvironment("Settings__MessageBroker", "SNS") + .WithEnvironment("Settings__S3Hosting", "Minio") + .WithEnvironment("AWS__Resources__SNSUrl", "http://host.docker.internal:5225/api/sns") + .WithEnvironment("AWS__Resources__MinioBucketName", "company-employee-bucket") + .WithReference(minio) + .WaitFor(minio) + .WaitFor(awsResources); + var client = builder.AddProject("client") .WithReference(gateway) .WaitFor(gateway); +builder.UseLocalStack(localstack); + builder.Build().Run(); \ No newline at end of file diff --git a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj index 4758735f..75f409ff 100644 --- a/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj +++ b/CompanyEmployee.AppHost/CompanyEmployee.AppHost.csproj @@ -13,12 +13,21 @@ + + + + + + Always + + + diff --git a/CompanyEmployee.AppHost/appsettings.json b/CompanyEmployee.AppHost/appsettings.json index 31c092aa..a6b256bb 100644 --- a/CompanyEmployee.AppHost/appsettings.json +++ b/CompanyEmployee.AppHost/appsettings.json @@ -5,5 +5,8 @@ "Microsoft.AspNetCore": "Warning", "Aspire.Hosting.Dcp": "Warning" } + }, + "LocalStack": { + "UseLocalStack": true } } diff --git a/CompanyEmployee.EventSink/CompanyEmployee.EventSink.csproj b/CompanyEmployee.EventSink/CompanyEmployee.EventSink.csproj new file mode 100644 index 00000000..e46a7122 --- /dev/null +++ b/CompanyEmployee.EventSink/CompanyEmployee.EventSink.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.EventSink/Controller/S3StorageController.cs b/CompanyEmployee.EventSink/Controller/S3StorageController.cs new file mode 100644 index 00000000..b543a488 --- /dev/null +++ b/CompanyEmployee.EventSink/Controller/S3StorageController.cs @@ -0,0 +1,68 @@ +using System.Text; +using System.Text.Json.Nodes; +using CompanyEmployee.EventSink.S3; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.EventSink.Controller; + +/// +/// Контроллер для взаимодейсвия с S3 +/// +/// Служба для работы с S3 +/// Логгер +[ApiController] +[Route("api/s3")] +public class S3StorageController(IS3Service s3Service, ILogger logger) : ControllerBase +{ + + /// + /// Метод для получения списка хранящихся в S3 файлов + /// + /// Список с ключами файлов + [HttpGet] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task>> ListFiles() + { + logger.LogInformation("Method {method} of {controller} was called", nameof(ListFiles), + nameof(S3StorageController)); + try + { + var list = await s3Service.GetFileList(); + logger.LogInformation("Got a list of {count} files from bucket", list.Count); + return Ok(list); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occured during {method} of {controller}", nameof(ListFiles), + nameof(S3StorageController)); + return BadRequest(ex); + } + } + + /// + /// Получает строковое представление хранящегося в S3 документа + /// + /// Ключ файла + /// Строковое представление файла + [HttpGet("{key}")] + [ProducesResponseType(200)] + [ProducesResponseType(500)] + public async Task> GetFile(string key) + { + logger.LogInformation("Method {method} of {controller} was called", nameof(GetFile), + nameof(S3StorageController)); + try + { + var node = await s3Service.DownloadFile(key); + logger.LogInformation("Received json of {size} bytes", Encoding.UTF8.GetByteCount(node.ToJsonString())); + return Ok(node); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occured during {method} of {controller}", nameof(GetFile), + nameof(S3StorageController)); + return BadRequest(ex); + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.EventSink/Controller/SnsSubscriberController.cs b/CompanyEmployee.EventSink/Controller/SnsSubscriberController.cs new file mode 100644 index 00000000..fa6b9939 --- /dev/null +++ b/CompanyEmployee.EventSink/Controller/SnsSubscriberController.cs @@ -0,0 +1,68 @@ +using System.Text; +using Amazon.SimpleNotificationService.Util; +using CompanyEmployee.EventSink.S3; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.EventSink.Controller; + +[ApiController] +[Route("api/sns")] +public class SnsSubscriberController(IS3Service s3Service, ILogger logger) : ControllerBase +{ + /// + /// Вебхук, который получает оповещения из SNS топика + /// + /// + /// Используется не только, чтобы получать оповещения, + /// но и для того, чтобы подтвердить подписку при + /// инициализации информационного обмена. + /// В любом случае должен возвращать 200 + /// + [HttpPost] + [ProducesResponseType(200)] + public async Task ReceiveMessage() + { + logger.LogInformation("SNS webhook was called"); + try + { + using var reader = new StreamReader(Request.Body, Encoding.UTF8); + var jsonContent = await reader.ReadToEndAsync(); + + var snsMessage = Message.ParseMessage(jsonContent); + + switch (snsMessage.Type) + { + case "SubscriptionConfirmation": + { + logger.LogInformation("SubscriptionConfirmation was received"); + using var httpClient = new HttpClient(); + var builder = new UriBuilder(new Uri(snsMessage.SubscribeURL)) + { + Scheme = "http", + Host = "localhost", + Port = 4566 + }; + var response = await httpClient.GetAsync(builder.Uri); + if (!response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(); + throw new Exception($"SubscriptionConfirmation returned {response.StatusCode}: {body}"); + } + logger.LogInformation("Subscription was successfully confirmed"); + break; + } + case "Notification": + { + await s3Service.UploadFile(snsMessage.MessageText); + logger.LogInformation("Notification was successfully processed"); + break; + } + } + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred while processing SNS notifications"); + } + return Ok(); + } +} \ No newline at end of file diff --git a/CompanyEmployee.EventSink/Messaging/SnsSubscriptionService.cs b/CompanyEmployee.EventSink/Messaging/SnsSubscriptionService.cs new file mode 100644 index 00000000..31242f46 --- /dev/null +++ b/CompanyEmployee.EventSink/Messaging/SnsSubscriptionService.cs @@ -0,0 +1,50 @@ +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using System.Net; + +namespace CompanyEmployee.EventSink.Messaging; + +/// +/// Служба для подписки на SNS на старте приложения +/// +/// Клиент SNS +/// Конфигурация +/// Логгер +public class SnsSubscriptionService( + IAmazonSimpleNotificationService snsClient, + IConfiguration configuration, + ILogger logger) +{ + /// + /// Уникальный идентификатор топика SNS + /// + private readonly string _topicArn = configuration["AWS:Resources:SNSTopicArn"] ?? + throw new KeyNotFoundException("SNS topic link was not found in configuration"); + + /// + /// Делает попытку подписаться на топик SNS + /// + public async Task SubscribeEndpoint() + { + logger.LogInformation("Sending subscride request for {topic}", _topicArn); + var endpoint = configuration["AWS:Resources:SNSUrl"]; + + var request = new SubscribeRequest + { + TopicArn = _topicArn, + Protocol = "http", + Endpoint = endpoint, + ReturnSubscriptionArn = true + }; + var response = await snsClient.SubscribeAsync(request); + if (response.HttpStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to subscribe to {topic}", _topicArn); + } + + else + { + logger.LogInformation("Subscription request for {topic} is successful, waiting for confirmation", _topicArn); + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.EventSink/Program.cs b/CompanyEmployee.EventSink/Program.cs new file mode 100644 index 00000000..2a6da7df --- /dev/null +++ b/CompanyEmployee.EventSink/Program.cs @@ -0,0 +1,41 @@ +using Amazon.SimpleNotificationService; +using CompanyEmployee.EventSink.Messaging; +using CompanyEmployee.EventSink.S3; +using CompanyEmployee.ServiceDefaults; +using LocalStack.Client.Extensions; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); +builder.AddMinioClient("minio"); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +var app = builder.Build(); + +var scope = app.Services.CreateScope(); +var snsService = scope.ServiceProvider.GetRequiredService(); +await snsService.SubscribeEndpoint(); + +scope = app.Services.CreateScope(); +var s3Service = scope.ServiceProvider.GetRequiredService(); +await s3Service.EnsureBucketExists(); + +app.MapDefaultEndpoints(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapControllers(); +app.Run(); \ No newline at end of file diff --git a/CompanyEmployee.EventSink/Properties/launchSettings.json b/CompanyEmployee.EventSink/Properties/launchSettings.json new file mode 100644 index 00000000..72fdf7cc --- /dev/null +++ b/CompanyEmployee.EventSink/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:48738", + "sslPort": 44332 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5225", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7252;http://localhost:5225", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CompanyEmployee.EventSink/S3/IS3Service.cs b/CompanyEmployee.EventSink/S3/IS3Service.cs new file mode 100644 index 00000000..21143be2 --- /dev/null +++ b/CompanyEmployee.EventSink/S3/IS3Service.cs @@ -0,0 +1,33 @@ +using System.Text.Json.Nodes; + +namespace CompanyEmployee.EventSink.S3; + +/// +/// Интерфейс службы для манипуляции файлами в объектном хранилище +/// +public interface IS3Service +{ + /// + /// Отправляет файл в хранилище + /// + /// Строковая репрезентация сохраняемого файла + public Task UploadFile(string fileData); + + /// + /// Получает список всех файлов из хранилища + /// + /// Список путей к файлам + public Task> GetFileList(); + + /// + /// Получает строковую репрезентацию файла из хранилища + /// + /// Путь к файлу в бакете + /// Строковая репрезентация прочтенного файла + public Task DownloadFile(string filePath); + + /// + /// Создает S3 бакет при необходимости + /// + public Task EnsureBucketExists(); +} \ No newline at end of file diff --git a/CompanyEmployee.EventSink/S3/S3MinioService.cs b/CompanyEmployee.EventSink/S3/S3MinioService.cs new file mode 100644 index 00000000..e6f001fe --- /dev/null +++ b/CompanyEmployee.EventSink/S3/S3MinioService.cs @@ -0,0 +1,131 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using Minio; +using Minio.DataModel.Args; + +namespace CompanyEmployee.EventSink.S3; + +/// +/// Cлужба, реализующая интерфейс IS3Service для манипуляции файлами в объектном хранилище +/// +/// S3 клиент +/// Конфигурация +/// Логер +public class S3MinioService(IMinioClient client, IConfiguration configuration, ILogger logger) + : IS3Service +{ + private readonly string _bucketName = configuration["AWS:Resources:MinioBucketName"] + ?? throw new KeyNotFoundException("S3 bucket name was not found in configuration"); + + /// + public async Task> GetFileList() + { + var request = new ListObjectsArgs() + .WithBucket(_bucketName) + .WithPrefix("") + .WithRecursive(true); + logger.LogInformation("Began listing files in {bucket}", _bucketName); + var responseList = client.ListObjectsEnumAsync(request); + + if (responseList == null) + logger.LogWarning("Received null response from {bucket}", _bucketName); + + var list = new List(); + await foreach (var response in responseList!) + list.Add(response.Key); + return list; + } + + /// + 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"]?.GetValue() ?? throw new ArgumentException("Passed JSON has invalid structure"); + + var bytes = Encoding.UTF8.GetBytes(fileData); + using var stream = new MemoryStream(bytes); + stream.Seek(0, SeekOrigin.Begin); + + logger.LogInformation("Began uploading company employee {file} onto {bucket}", id, _bucketName); + + var request = new PutObjectArgs() + .WithBucket(_bucketName) + .WithStreamData(stream) + .WithObjectSize(bytes.Length) + .WithObject($"company_employee_{id}.json"); + + var response = await client.PutObjectAsync(request); + + if (response.ResponseStatusCode != HttpStatusCode.OK) + { + logger.LogError("Failed to upload employee {file}: {code}", id, response.ResponseStatusCode); + return false; + } + logger.LogInformation("Finished uploading employee {file} to {bucket}", id, _bucketName); + return true; + } + + /// + public async Task DownloadFile(string filePath) + { + logger.LogInformation("Began downloading {file} from {bucket}", filePath, _bucketName); + try + { + var memoryStream = new MemoryStream(); + + var request = new GetObjectArgs() + .WithBucket(_bucketName) + .WithObject(filePath) + .WithCallbackStream(async (stream, cancellationToken) => + { + await stream.CopyToAsync(memoryStream, cancellationToken); + memoryStream.Seek(0, SeekOrigin.Begin); + }); + + var response = await client.GetObjectAsync(request); + + if (response == null) + { + logger.LogError("Failed to download {file}", filePath); + throw new InvalidOperationException($"Error occurred downloading {filePath} - object is null"); + } + + using var reader = new StreamReader(memoryStream, Encoding.UTF8); + + return JsonNode.Parse(reader.ReadToEnd()) ?? + throw new InvalidOperationException($"Downloaded document is not a valid JSON"); + } + catch (Exception ex) + { + logger.LogError(ex, "Exception occurred during {file} downloading ", filePath); + throw; + } + } + + /// + public async Task EnsureBucketExists() + { + logger.LogInformation("Checking whether {bucket} exists", _bucketName); + try + { + var request = new BucketExistsArgs().WithBucket(_bucketName); + + var exists = await client.BucketExistsAsync(request); + if (!exists) + { + logger.LogInformation("Creating {bucket}", _bucketName); + var createRequest = new MakeBucketArgs().WithBucket(_bucketName); + await client.MakeBucketAsync(createRequest); + + return; + } + logger.LogInformation("{bucket} exists", _bucketName); + } + catch (Exception ex) + { + logger.LogError(ex, "Unhandled exception occurred during {bucket} check", _bucketName); + throw; + } + } +} \ No newline at end of file diff --git a/CompanyEmployee.EventSink/appsettings.Development.json b/CompanyEmployee.EventSink/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CompanyEmployee.EventSink/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployee.EventSink/appsettings.json b/CompanyEmployee.EventSink/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/CompanyEmployee.EventSink/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj b/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj index c77f42f1..78ed7057 100644 --- a/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj +++ b/CompanyEmployee.Generator/CompanyEmployee.Generator.csproj @@ -10,6 +10,9 @@ + + + diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs index a41c1deb..11592601 100644 --- a/CompanyEmployee.Generator/Program.cs +++ b/CompanyEmployee.Generator/Program.cs @@ -1,5 +1,8 @@ -using CompanyEmployee.ServiceDefaults; +using Amazon.SimpleNotificationService; +using CompanyEmployee.Generator.Messaging; +using CompanyEmployee.ServiceDefaults; using CompanyEmployee.Generator.Service; +using LocalStack.Client.Extensions; var builder = WebApplication.CreateBuilder(args); @@ -14,6 +17,10 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +builder.Services.AddLocalStack(builder.Configuration); +builder.Services.AddAwsService(); var app = builder.Build(); diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs index 26d8fa4c..039b7bcf 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -16,6 +16,7 @@ ILogger logger private static readonly string[] _grade = ["Junior", "Middle", "Senior"]; + /// public CompanyEmployeeDto Generate(int employeeId) { var faker = new Faker("ru") diff --git a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs index 22407a26..f79ec7b2 100644 --- a/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -1,5 +1,6 @@ using System.Text.Json; using CompanyEmployee.Generator.Dto; +using CompanyEmployee.Generator.Messaging; using Microsoft.Extensions.Caching.Distributed; namespace CompanyEmployee.Generator.Service; @@ -8,11 +9,13 @@ namespace CompanyEmployee.Generator.Service; /// Сервис получения сотрудника компании /// /// Генератор сотрудника по идентификатору +/// Служба отправки сообщений в брокер /// Сервис кэширования /// Конфигурация приложения /// Логгер public class CompanyEmployeeService( ICompanyEmployeeGenerator generator, + IProducerService producerService, IDistributedCache cache, IConfiguration configuration, ILogger logger @@ -22,6 +25,7 @@ ILogger logger private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + /// public async Task GetByIdAsync(int employeeId, CancellationToken token) { var cacheKey = _companyEmployeeCachePrefix + employeeId; @@ -47,6 +51,8 @@ public async Task GetByIdAsync(int employeeId, CancellationT } companyEmployee = generator.Generate(employeeId); + + await producerService.SendMessage(companyEmployee); var ttlSeconds = configuration.GetValue("CompanyEmployeeCache:TtlSeconds", 600); var cacheOpts = new DistributedCacheEntryOptions diff --git a/CompanyEmployee.Tests/CompanyEmployee.Tests.csproj b/CompanyEmployee.Tests/CompanyEmployee.Tests.csproj new file mode 100644 index 00000000..51824867 --- /dev/null +++ b/CompanyEmployee.Tests/CompanyEmployee.Tests.csproj @@ -0,0 +1,36 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CompanyEmployee.Tests/IntegrationTests.cs b/CompanyEmployee.Tests/IntegrationTests.cs new file mode 100644 index 00000000..0f41dde7 --- /dev/null +++ b/CompanyEmployee.Tests/IntegrationTests.cs @@ -0,0 +1,139 @@ +using System.Text.Json; +using Aspire.Hosting; +using CompanyEmployee.Generator.Dto; +using Microsoft.Extensions.Logging; +using Projects; +using Xunit.Abstractions; + +namespace CompanyEmployee.Tests; + +/// +/// Интеграционные тесты для проверки микросервисного пайплайна +/// +/// Служба журналирования юнит-тестов +public class IntegrationTests(ITestOutputHelper output) : IAsyncLifetime +{ + private static readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private IDistributedApplicationTestingBuilder? _builder; + private DistributedApplication? _app; + private HttpClient? _gatewayClient; + private HttpClient? _s3Client; + + /// + public async Task InitializeAsync() + { + var cancellationToken = CancellationToken.None; + + _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"); + _s3Client = _app.CreateHttpClient("event-sink", "http"); + } + + /// + public async Task DisposeAsync() + { + await _app!.StopAsync(); + await _app.DisposeAsync(); + await _builder!.DisposeAsync(); + } + + /// + /// Проверка положительного сценария: + /// 1. Запрос возвращает сгенерированного сотрудника + /// 2. Идентичный сотрудник сохраняется в S3 + /// + [Fact] + public async Task SuccessPipelineTest() + { + var id = 0; + + var response = await _gatewayClient!.GetAsync($"/company-employee?id={id}"); + var generatedEmployee = + JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync(), _jsonOptions); + + var s3Employee = await GetEmployeeFromS3(id); + + Assert.NotNull(generatedEmployee); + Assert.NotNull(s3Employee); + Assert.Equivalent(generatedEmployee, s3Employee, strict: true); + } + + /// + /// Проверка обработки некорректных id + /// + /// id сотрудника + [Theory] + [InlineData("-1")] + [InlineData("qwe")] + public async Task IncorrectEmployeeIdTest(string id) + { + var request = $"/company-employee?id={id}"; + + var response = await _gatewayClient!.GetAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + /// + /// Проверка кэширования - при запросах с одинаковым id возвращаются одинаковые сотрудники + /// + [Fact] + public async Task CachingTest() + { + var id = 0; + + var response = await _gatewayClient!.GetAsync($"/company-employee?id={id}"); + var firstEmployee = + JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync(), _jsonOptions); + + response = await _gatewayClient!.GetAsync($"/company-employee?id={id}"); + var secondEmployee = + JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync(), _jsonOptions); + + Assert.NotNull(firstEmployee); + Assert.NotNull(secondEmployee); + Assert.Equivalent(firstEmployee, secondEmployee); + } + + /// + /// Получение сотрудника из S3 + /// + /// id сотрудника + /// DTO сотрудника компании + /// Выбрасывается, если сотрудник не найден в S3 + private async Task GetEmployeeFromS3(int id) + { + var endTime = DateTime.UtcNow + TimeSpan.FromSeconds(10); + var fileName = $"company_employee_{id}.json"; + + while (DateTime.UtcNow < endTime) + { + var file = await _s3Client!.GetAsync($"/api/s3/{fileName}"); + if (file.IsSuccessStatusCode) + { + return JsonSerializer.Deserialize(await file.Content.ReadAsStringAsync(), + _jsonOptions); + } + + await Task.Delay(500); + } + + throw new TimeoutException($"File with id {id} not found in S3"); + } +} \ No newline at end of file From 24fec4df88fa633ca71fc58f9f0e82e70be58135 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Mon, 27 Apr 2026 14:16:56 +0400 Subject: [PATCH 11/12] fix lab --- CompanyEmployee.EventSink/Program.cs | 5 ++--- CompanyEmployee.Tests/IntegrationTests.cs | 10 ++++------ 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/CompanyEmployee.EventSink/Program.cs b/CompanyEmployee.EventSink/Program.cs index 2a6da7df..ffe7bb5f 100644 --- a/CompanyEmployee.EventSink/Program.cs +++ b/CompanyEmployee.EventSink/Program.cs @@ -23,10 +23,9 @@ var scope = app.Services.CreateScope(); var snsService = scope.ServiceProvider.GetRequiredService(); -await snsService.SubscribeEndpoint(); - -scope = app.Services.CreateScope(); var s3Service = scope.ServiceProvider.GetRequiredService(); + +await snsService.SubscribeEndpoint(); await s3Service.EnsureBucketExists(); app.MapDefaultEndpoints(); diff --git a/CompanyEmployee.Tests/IntegrationTests.cs b/CompanyEmployee.Tests/IntegrationTests.cs index 0f41dde7..875677cc 100644 --- a/CompanyEmployee.Tests/IntegrationTests.cs +++ b/CompanyEmployee.Tests/IntegrationTests.cs @@ -18,7 +18,6 @@ public class IntegrationTests(ITestOutputHelper output) : IAsyncLifetime PropertyNameCaseInsensitive = true }; - private IDistributedApplicationTestingBuilder? _builder; private DistributedApplication? _app; private HttpClient? _gatewayClient; private HttpClient? _s3Client; @@ -28,9 +27,9 @@ public async Task InitializeAsync() { var cancellationToken = CancellationToken.None; - _builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); - _builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; - _builder.Services.AddLogging(logging => + var builder = await DistributedApplicationTestingBuilder.CreateAsync(cancellationToken); + builder.Configuration["DcpPublisher:RandomizePorts"] = "false"; + builder.Services.AddLogging(logging => { logging.AddXUnit(output); logging.SetMinimumLevel(LogLevel.Debug); @@ -38,7 +37,7 @@ public async Task InitializeAsync() logging.AddFilter("Aspire.Hosting", LogLevel.Debug); }); - _app = await _builder.BuildAsync(cancellationToken); + _app = await builder.BuildAsync(cancellationToken); await _app.StartAsync(cancellationToken); _gatewayClient = _app.CreateHttpClient("api-gateway", "http"); @@ -50,7 +49,6 @@ public async Task DisposeAsync() { await _app!.StopAsync(); await _app.DisposeAsync(); - await _builder!.DisposeAsync(); } /// From a89090c3fedde131bd99c348dbe677f0c8aab195 Mon Sep 17 00:00:00 2001 From: dedrowe Date: Wed, 29 Apr 2026 22:54:51 +0400 Subject: [PATCH 12/12] fix lab --- CompanyEmployee.EventSink/Program.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/CompanyEmployee.EventSink/Program.cs b/CompanyEmployee.EventSink/Program.cs index ffe7bb5f..553c7fe8 100644 --- a/CompanyEmployee.EventSink/Program.cs +++ b/CompanyEmployee.EventSink/Program.cs @@ -21,12 +21,14 @@ var app = builder.Build(); -var scope = app.Services.CreateScope(); -var snsService = scope.ServiceProvider.GetRequiredService(); -var s3Service = scope.ServiceProvider.GetRequiredService(); +using (var scope = app.Services.CreateScope()) +{ + var snsService = scope.ServiceProvider.GetRequiredService(); + var s3Service = scope.ServiceProvider.GetRequiredService(); -await snsService.SubscribeEndpoint(); -await s3Service.EnsureBucketExists(); + await snsService.SubscribeEndpoint(); + await s3Service.EnsureBucketExists(); +} app.MapDefaultEndpoints();