From 4ff96078c19cdf9cb70e7e3b18e23c564cd91dee Mon Sep 17 00:00:00 2001 From: AvtoBBus <113329450+AvtoBBus@users.noreply.github.com> Date: Thu, 5 Mar 2026 14:17:58 +0400 Subject: [PATCH 1/3] adding AppHost and Generator with caching --- AspireApp1/AspireApp1.AppHost/AppHost.cs | 3 + .../AspireApp1.AppHost.csproj | 17 +++ .../Properties/launchSettings.json | 29 +++++ .../appsettings.Development.json | 8 ++ .../AspireApp1.AppHost/appsettings.json | 9 ++ .../CompanyEmployees.ServiceDefaults.csproj | 28 +++++ .../AspireApp1.ServiceDefaults/Extensions.cs | 104 ++++++++++++++++ Client.Wasm/Client.Wasm.csproj | 1 + Client.Wasm/Components/StudentCard.razor | 10 +- Client.Wasm/Properties/launchSettings.json | 12 +- Client.Wasm/wwwroot/appsettings.json | 4 +- CloudDevelopment.sln | 27 ++++ .../CompanyEmployees.AppHost.csproj | 24 ++++ CompanyEmployees.AppHost/Program.cs | 13 ++ .../Properties/launchSettings.json | 29 +++++ .../appsettings.Development.json | 8 ++ CompanyEmployees.AppHost/appsettings.json | 9 ++ .../CompanyEmployees.Generator.csproj | 20 +++ .../Models/CompanyEmployee.cs | 64 ++++++++++ CompanyEmployees.Generator/Program.cs | 58 +++++++++ .../Properties/launchSettings.json | 23 ++++ .../Services/CompanyEmployeeGenerator.cs | 117 ++++++++++++++++++ .../Services/CompanyEmployeeService.cs | 68 ++++++++++ .../appsettings.Development.json | 8 ++ CompanyEmployees.Generator/appsettings.json | 8 ++ 25 files changed, 689 insertions(+), 12 deletions(-) create mode 100644 AspireApp1/AspireApp1.AppHost/AppHost.cs create mode 100644 AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj create mode 100644 AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json create mode 100644 AspireApp1/AspireApp1.AppHost/appsettings.Development.json create mode 100644 AspireApp1/AspireApp1.AppHost/appsettings.json create mode 100644 AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj create mode 100644 AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs create mode 100644 CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj create mode 100644 CompanyEmployees.AppHost/Program.cs create mode 100644 CompanyEmployees.AppHost/Properties/launchSettings.json create mode 100644 CompanyEmployees.AppHost/appsettings.Development.json create mode 100644 CompanyEmployees.AppHost/appsettings.json create mode 100644 CompanyEmployees.Generator/CompanyEmployees.Generator.csproj create mode 100644 CompanyEmployees.Generator/Models/CompanyEmployee.cs create mode 100644 CompanyEmployees.Generator/Program.cs create mode 100644 CompanyEmployees.Generator/Properties/launchSettings.json create mode 100644 CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs create mode 100644 CompanyEmployees.Generator/Services/CompanyEmployeeService.cs create mode 100644 CompanyEmployees.Generator/appsettings.Development.json create mode 100644 CompanyEmployees.Generator/appsettings.json diff --git a/AspireApp1/AspireApp1.AppHost/AppHost.cs b/AspireApp1/AspireApp1.AppHost/AppHost.cs new file mode 100644 index 0000000..c62c3a0 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/AppHost.cs @@ -0,0 +1,3 @@ +var builder = DistributedApplication.CreateBuilder(args); + +builder.Build().Run(); diff --git a/AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj b/AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj new file mode 100644 index 0000000..8fa2570 --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj @@ -0,0 +1,17 @@ + + + + + + Exe + net8.0 + enable + enable + d412956e-dd1b-41e4-9327-6d3cb514b1d3 + + + + + + + diff --git a/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json b/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..815321e --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17200;http://localhost:15157", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21258", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22276" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15157", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19082", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20132" + } + } + } +} diff --git a/AspireApp1/AspireApp1.AppHost/appsettings.Development.json b/AspireApp1/AspireApp1.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/AspireApp1/AspireApp1.AppHost/appsettings.json b/AspireApp1/AspireApp1.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/AspireApp1/AspireApp1.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj b/AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj new file mode 100644 index 0000000..4e142da --- /dev/null +++ b/AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + enable + true + Debug;Release;123 + + + + + + + + + + + + + + + + + + + + diff --git a/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs b/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..f1836a6 --- /dev/null +++ b/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs @@ -0,0 +1,104 @@ +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; +using Serilog; + +namespace CompanyEmployees.ServiceDefaults; + +public static class Extensions +{ + public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) + { + builder.ConfigureSerilog(); + builder.ConfigureOpenTelemetry(); + builder.AddDefaultHealthChecks(); + builder.Services.AddServiceDiscovery(); + builder.Services.ConfigureHttpClientDefaults(http => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + return builder; + } + + public static IHostApplicationBuilder ConfigureSerilog(this IHostApplicationBuilder builder) + { + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(builder.Configuration) + .Enrich.FromLogContext() + .Enrich.WithEnvironmentName() + .Enrich.WithThreadId() + .Enrich.WithMachineName() + .WriteTo.Console(outputTemplate: + "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}") + .CreateLogger(); + + builder.Services.AddSerilog(); + + return builder; + } + + public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder) + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + return builder; + } + + public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder) + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + app.MapHealthChecks("/health"); + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + + return app; + } +} \ No newline at end of file diff --git a/Client.Wasm/Client.Wasm.csproj b/Client.Wasm/Client.Wasm.csproj index 0ba9f90..0c323bf 100644 --- a/Client.Wasm/Client.Wasm.csproj +++ b/Client.Wasm/Client.Wasm.csproj @@ -4,6 +4,7 @@ net8.0 enable enable + Debug;Release;123 diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..a53bf00 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,12 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 "Кэширование" + + Вариант №8 "Сотрудник компании" + + Выполнена Земляновым Владимиром 6511 + Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea..6ad691a 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -12,9 +12,9 @@ "http": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", - "applicationUrl": "http://localhost:5127", + "applicationUrl": "http://localhost:5128", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -22,20 +22,20 @@ "https": { "commandName": "Project", "dotnetRunMessages": true, - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", - "applicationUrl": "https://localhost:7282;http://localhost:5127", + "applicationUrl": "https://localhost:7283;http://localhost:5128", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", - "launchBrowser": true, + "launchBrowser": false, "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } -} +} \ No newline at end of file diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab..fcd8f03 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" -} + "BaseAddress": "https://localhost:7171/employee" +} \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..cf6c038 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -5,16 +5,43 @@ 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}") = "CompanyEmployees.AppHost", "CompanyEmployees.AppHost\CompanyEmployees.AppHost.csproj", "{96FC536F-9C20-45C4-B624-F3E2DEE96BA3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.Generator", "CompanyEmployees.Generator\CompanyEmployees.Generator.csproj", "{418E6A76-7DE1-04F1-F18A-9A7C9ED44857}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.ServiceDefaults", "AspireApp1\AspireApp1.ServiceDefaults\CompanyEmployees.ServiceDefaults.csproj", "{F9222B91-99B7-2420-265D-E51F0CE78C78}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + 123|Any CPU = 123|Any CPU Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.123|Any CPU.ActiveCfg = 123|Any CPU + {AE7EEA74-2FE0-136F-D797-854FD87E022A}.123|Any CPU.Build.0 = 123|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU + {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.123|Any CPU.ActiveCfg = 123|Any CPU + {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.123|Any CPU.Build.0 = 123|Any CPU + {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Release|Any CPU.Build.0 = Release|Any CPU + {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.123|Any CPU.ActiveCfg = Release|Any CPU + {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.123|Any CPU.Build.0 = Release|Any CPU + {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Debug|Any CPU.Build.0 = Debug|Any CPU + {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Release|Any CPU.ActiveCfg = Release|Any CPU + {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Release|Any CPU.Build.0 = Release|Any CPU + {F9222B91-99B7-2420-265D-E51F0CE78C78}.123|Any CPU.ActiveCfg = Debug|Any CPU + {F9222B91-99B7-2420-265D-E51F0CE78C78}.123|Any CPU.Build.0 = Debug|Any CPU + {F9222B91-99B7-2420-265D-E51F0CE78C78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F9222B91-99B7-2420-265D-E51F0CE78C78}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F9222B91-99B7-2420-265D-E51F0CE78C78}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F9222B91-99B7-2420-265D-E51F0CE78C78}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj b/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj new file mode 100644 index 0000000..7e140d3 --- /dev/null +++ b/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + enable + enable + enable + true + Debug;Release;123 + + + + + + + + + + + + + + + diff --git a/CompanyEmployees.AppHost/Program.cs b/CompanyEmployees.AppHost/Program.cs new file mode 100644 index 0000000..6e2759c --- /dev/null +++ b/CompanyEmployees.AppHost/Program.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis") + .WithRedisCommander(); + +var generator = builder.AddProject("generator") + .WithReference(redis) + .WithExternalHttpEndpoints(); + +builder.AddProject("client") + .WithReference(generator); + +builder.Build().Run(); \ No newline at end of file diff --git a/CompanyEmployees.AppHost/Properties/launchSettings.json b/CompanyEmployees.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..09cd82d --- /dev/null +++ b/CompanyEmployees.AppHost/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17170;http://localhost:15170", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21170", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22170" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15170", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19170", + "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20170" + } + } + } +} \ No newline at end of file diff --git a/CompanyEmployees.AppHost/appsettings.Development.json b/CompanyEmployees.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CompanyEmployees.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployees.AppHost/appsettings.json b/CompanyEmployees.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/CompanyEmployees.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj b/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj new file mode 100644 index 0000000..114d0c4 --- /dev/null +++ b/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + Debug;Release;123 + + + + + + + + + + + + + diff --git a/CompanyEmployees.Generator/Models/CompanyEmployee.cs b/CompanyEmployees.Generator/Models/CompanyEmployee.cs new file mode 100644 index 0000000..8244082 --- /dev/null +++ b/CompanyEmployees.Generator/Models/CompanyEmployee.cs @@ -0,0 +1,64 @@ +namespace CompanyEmployees.Generator.Models; + +/// +/// Модель сотрудника компании +/// +public class CompanyEmployeeModel +{ + /// + /// Идентификатор сотрудника в системе + /// + public int Id { get; set; } + + /// + /// ФИО + ///
+ /// Конкатенация фамилии, имени и отчества через пробел + ///
+ ///
+ public required string FullName { get; set; } + + /// + /// Должность
+ /// Выбирается из справочника профессий (“Developer”, “Manager”, “Analyst” и т.д.) и справочника суффиксов к ним (“Junior”, “Middle”, “Senior” и т.д.) + ///
+ public required string Position { get; set; } + + /// + /// Отдел + /// + public required string Section { get; set; } + + /// + /// Дата приема
+ /// Ограничение: не более 10 лет назад от текущей даты + ///
+ public required DateOnly AdmissionDate { get; set; } + + /// + /// Оклад
+ /// Значение коррелирует с суффиксом должности + ///
+ public required decimal Salary { get; set; } + + /// + /// Электронная почта + /// + public required string Email { get; set; } + + /// + /// Номер телефона формата +7(***)***-**-** + /// + public required string PhoneNumber { get; set; } + + /// + /// Индикатор увольнения + /// + public required bool Dismissal { get; set; } = false; + + /// + /// Дата увольнения
+ /// При отсутствии индикатора увольнения дата увольнения не заполняется + ///
+ public DateOnly? DismissalDate { get; set; } +} diff --git a/CompanyEmployees.Generator/Program.cs b/CompanyEmployees.Generator/Program.cs new file mode 100644 index 0000000..582edef --- /dev/null +++ b/CompanyEmployees.Generator/Program.cs @@ -0,0 +1,58 @@ +using CompanyEmployees.Generator.Services; +using CompanyEmployees.ServiceDefaults; +using Serilog; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +builder.AddRedisDistributedCache("redis"); + +builder.Services.AddSingleton(); +builder.Services.AddScoped(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); +}); + +var app = builder.Build(); + +app.UseCors(); +app.UseSerilogRequestLogging(); + +app.MapDefaultEndpoints(); + +app.MapGet("/employee", async ( + int id, + CompanyEmployeeService service, + ILogger logger, + CancellationToken cancellationToken) => +{ + logger.LogInformation("Received request for company employee with ID: {Id}", id); + + if (id <= 0) + { + logger.LogWarning("Received invalid ID: {Id}", id); + return Results.BadRequest(new { error = "ID must be a positive number" }); + } + + try + { + var application = await service.GetByIdAsync(id, cancellationToken); + return Results.Ok(application); + } + catch (Exception ex) + { + logger.LogError(ex, "Error while getting company employee {Id}", id); + return Results.Problem("An error occurred while processing the request"); + } +}) +.WithName("GetCompanyEmployee"); + +app.Run(); \ No newline at end of file diff --git a/CompanyEmployees.Generator/Properties/launchSettings.json b/CompanyEmployees.Generator/Properties/launchSettings.json new file mode 100644 index 0000000..ea1476c --- /dev/null +++ b/CompanyEmployees.Generator/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5171", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7171;http://localhost:5171", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs b/CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs new file mode 100644 index 0000000..2362b33 --- /dev/null +++ b/CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs @@ -0,0 +1,117 @@ +using Bogus; +using Bogus.DataSets; +using CompanyEmployees.Generator.Models; + +namespace CompanyEmployees.Generator.Services; + +/// +/// Генератор сотрудника по идентификатору +/// +/// Логгер +public class CompanyEmployeeGenerator(ILogger logger) +{ + /// + /// Справочник профессий сотрудников + /// + private static readonly string[] _positionProfessions = + [ + "Developer", + "Manager", + "Analyst", + "DevOps Engineer", + "QA Engineer", + "System Architect" + ]; + + /// + /// Справочник суффиксов для профессий + /// + private enum PositionSuffix + { + Junior = 0, + Middle = 1, + Senior = 2, + TeamLead = 3 + }; + + /// + /// Словарь множителей на основе суффиксов профессий + /// + private static readonly Dictionary _positionSuffixSalaryMultipliers = new() + { + [PositionSuffix.Junior] = 1m, + [PositionSuffix.Middle] = 1.5m, + [PositionSuffix.Senior] = 2.1m, + [PositionSuffix.TeamLead] = 2.6m + }; + + private readonly ILogger _logger = logger; + + /// + /// Функция для генерации сотрудника на основе параметра id + /// + /// Идентификатор сотрудника в системе + /// Сгенерированные данные о сотруднике + public CompanyEmployeeModel Generate(int id) + { + _logger.LogInformation("Start generating company employee application with ID: {Id}", id); + + var faker = new Faker("ru") + .UseSeed(id) + .RuleFor(x => x.Id, _ => id) + .RuleFor(x => x.FullName, f => GenerateEmployeeFullName(f)) + .RuleFor(x => x.Position, f => GenerateEmployeePosition(f)) + .RuleFor(x => x.Section, f => f.Commerce.Department()) + .RuleFor(x => x.AdmissionDate, f => f.Date.PastDateOnly(10)) + .RuleFor(x => x.Salary, (f, x) => GenerateEmployeeSalary(f, x)) + .RuleFor(x => x.Email, f => f.Internet.Email()) + .RuleFor(x => x.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##")) + .RuleFor(x => x.Dismissal, f => f.Random.Bool()) + .RuleFor(x => x.DismissalDate, (f, x) => GenerateEmployeeDismissalDate(f, x)); + + _logger.LogInformation("Finally generate employee with ID: {Id}", id); + + return faker.Generate(); + } + + private static string GenerateEmployeeFullName(Faker faker) + { + var gender = faker.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); + + var firstName = faker.Name.FirstName(gender); + var lastName = faker.Name.LastName(gender); + var patronymic = faker.Name.FirstName(gender) + (gender == Name.Gender.Male ? "еевич" : "еевна"); + + return string.Join(' ', firstName, lastName, patronymic); + } + + private static string GenerateEmployeePosition(Faker faker) + { + return string.Join(' ', faker.PickRandom(_positionProfessions), faker.PickRandom()); + } + + private static decimal GenerateEmployeeSalary(Faker faker, CompanyEmployeeModel x) + { + var baseSalary = faker.Random.Decimal(100, 200); + var finalSalary = baseSalary; + + foreach (var kvp in _positionSuffixSalaryMultipliers) + { + if (x.Position.Contains(kvp.Key.ToString())) + { + finalSalary = baseSalary * kvp.Value; + break; + } + } + + return Math.Round(baseSalary, 2); + } + + private static DateOnly? GenerateEmployeeDismissalDate(Faker faker, CompanyEmployeeModel x) + { + + if (x.Dismissal) return null; + + return faker.Date.BetweenDateOnly(x.AdmissionDate, DateOnly.FromDateTime(DateTime.UtcNow)); + } +} diff --git a/CompanyEmployees.Generator/Services/CompanyEmployeeService.cs b/CompanyEmployees.Generator/Services/CompanyEmployeeService.cs new file mode 100644 index 0000000..6be51c9 --- /dev/null +++ b/CompanyEmployees.Generator/Services/CompanyEmployeeService.cs @@ -0,0 +1,68 @@ +using CompanyEmployees.Generator.Models; +using Microsoft.Extensions.Caching.Distributed; +using System.Text.Json; + +namespace CompanyEmployees.Generator.Services; + +/// +/// Сервис для работы с сотрудниками компании
+/// Каждый сгенерированный сотрудник сохраняется в кэш, если ранее он небыл получен
+/// В ином случае значение берется из кэша +///
+/// Генератор необходимый для создания сотрудника +/// Кэш хранящий ранее сгенерированных сотрудников +/// Логгер +public class CompanyEmployeeService( + CompanyEmployeeGenerator generator, + IDistributedCache cache, + ILogger logger +) +{ + private readonly CompanyEmployeeGenerator _generator = generator; + private readonly IDistributedCache _cache = cache; + private readonly ILogger _logger = logger; + + private static readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(5); + private const string CacheKeyPrefix = "company-employee:"; + + /// + /// Функция для генерации или взятия из кэша сотрудника по id + /// + /// Id сотрудника + /// Токен для отмены операции + /// + public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default) + { + var cacheKey = $"{CacheKeyPrefix}{id}"; + + _logger.LogInformation("Request for credit application with ID: {Id}", id); + + var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken); + + if (!string.IsNullOrEmpty(cachedData)) + { + _logger.LogInformation("Credit application {Id} found in cache", id); + var cachedApplication = JsonSerializer.Deserialize(cachedData); + return cachedApplication!; + } + + _logger.LogInformation("Credit application {Id} not found in cache, generating new one", id); + + var application = _generator.Generate(id); + + var serializedData = JsonSerializer.Serialize(application); + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = _cacheExpiration + }; + + await _cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken); + + _logger.LogInformation( + "Credit application {Id} saved to cache with TTL {CacheExpiration} minutes", + id, + _cacheExpiration.TotalMinutes); + + return application; + } +} diff --git a/CompanyEmployees.Generator/appsettings.Development.json b/CompanyEmployees.Generator/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CompanyEmployees.Generator/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CompanyEmployees.Generator/appsettings.json b/CompanyEmployees.Generator/appsettings.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/CompanyEmployees.Generator/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} From 21dd0d5f9c87b1aa404c6189f92fc3cb62af8bf3 Mon Sep 17 00:00:00 2001 From: AvtoBBus <113329450+AvtoBBus@users.noreply.github.com> Date: Thu, 5 Mar 2026 14:18:38 +0400 Subject: [PATCH 2/3] some fix --- AspireApp1/AspireApp1.AppHost/AppHost.cs | 3 - .../AspireApp1.AppHost.csproj | 17 --- .../Properties/launchSettings.json | 29 ----- .../appsettings.Development.json | 8 -- .../AspireApp1.AppHost/appsettings.json | 9 -- .../CompanyEmployees.ServiceDefaults.csproj | 28 ----- .../AspireApp1.ServiceDefaults/Extensions.cs | 104 ------------------ 7 files changed, 198 deletions(-) delete mode 100644 AspireApp1/AspireApp1.AppHost/AppHost.cs delete mode 100644 AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj delete mode 100644 AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json delete mode 100644 AspireApp1/AspireApp1.AppHost/appsettings.Development.json delete mode 100644 AspireApp1/AspireApp1.AppHost/appsettings.json delete mode 100644 AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj delete mode 100644 AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs diff --git a/AspireApp1/AspireApp1.AppHost/AppHost.cs b/AspireApp1/AspireApp1.AppHost/AppHost.cs deleted file mode 100644 index c62c3a0..0000000 --- a/AspireApp1/AspireApp1.AppHost/AppHost.cs +++ /dev/null @@ -1,3 +0,0 @@ -var builder = DistributedApplication.CreateBuilder(args); - -builder.Build().Run(); diff --git a/AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj b/AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj deleted file mode 100644 index 8fa2570..0000000 --- a/AspireApp1/AspireApp1.AppHost/AspireApp1.AppHost.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - Exe - net8.0 - enable - enable - d412956e-dd1b-41e4-9327-6d3cb514b1d3 - - - - - - - diff --git a/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json b/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json deleted file mode 100644 index 815321e..0000000 --- a/AspireApp1/AspireApp1.AppHost/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "profiles": { - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "https://localhost:17200;http://localhost:15157", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development", - "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21258", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22276" - } - }, - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://localhost:15157", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development", - "DOTNET_ENVIRONMENT": "Development", - "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19082", - "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20132" - } - } - } -} diff --git a/AspireApp1/AspireApp1.AppHost/appsettings.Development.json b/AspireApp1/AspireApp1.AppHost/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/AspireApp1/AspireApp1.AppHost/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/AspireApp1/AspireApp1.AppHost/appsettings.json b/AspireApp1/AspireApp1.AppHost/appsettings.json deleted file mode 100644 index 31c092a..0000000 --- a/AspireApp1/AspireApp1.AppHost/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning", - "Aspire.Hosting.Dcp": "Warning" - } - } -} diff --git a/AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj b/AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj deleted file mode 100644 index 4e142da..0000000 --- a/AspireApp1/AspireApp1.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - net8.0 - enable - enable - true - Debug;Release;123 - - - - - - - - - - - - - - - - - - - - diff --git a/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs b/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs deleted file mode 100644 index f1836a6..0000000 --- a/AspireApp1/AspireApp1.ServiceDefaults/Extensions.cs +++ /dev/null @@ -1,104 +0,0 @@ -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; -using Serilog; - -namespace CompanyEmployees.ServiceDefaults; - -public static class Extensions -{ - public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) - { - builder.ConfigureSerilog(); - builder.ConfigureOpenTelemetry(); - builder.AddDefaultHealthChecks(); - builder.Services.AddServiceDiscovery(); - builder.Services.ConfigureHttpClientDefaults(http => - { - http.AddStandardResilienceHandler(); - http.AddServiceDiscovery(); - }); - - return builder; - } - - public static IHostApplicationBuilder ConfigureSerilog(this IHostApplicationBuilder builder) - { - Log.Logger = new LoggerConfiguration() - .ReadFrom.Configuration(builder.Configuration) - .Enrich.FromLogContext() - .Enrich.WithEnvironmentName() - .Enrich.WithThreadId() - .Enrich.WithMachineName() - .WriteTo.Console(outputTemplate: - "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}") - .CreateLogger(); - - builder.Services.AddSerilog(); - - return builder; - } - - public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) - { - builder.Logging.AddOpenTelemetry(logging => - { - logging.IncludeFormattedMessage = true; - logging.IncludeScopes = true; - }); - - builder.Services.AddOpenTelemetry() - .WithMetrics(metrics => - { - metrics.AddAspNetCoreInstrumentation() - .AddHttpClientInstrumentation() - .AddRuntimeInstrumentation(); - }) - .WithTracing(tracing => - { - tracing.AddAspNetCoreInstrumentation() - .AddHttpClientInstrumentation(); - }); - - builder.AddOpenTelemetryExporters(); - - return builder; - } - - private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder) - { - var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); - - if (useOtlpExporter) - { - builder.Services.AddOpenTelemetry().UseOtlpExporter(); - } - - return builder; - } - - public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder) - { - builder.Services.AddHealthChecks() - .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); - - return builder; - } - - public static WebApplication MapDefaultEndpoints(this WebApplication app) - { - app.MapHealthChecks("/health"); - app.MapHealthChecks("/alive", new HealthCheckOptions - { - Predicate = r => r.Tags.Contains("live") - }); - - return app; - } -} \ No newline at end of file From 5d39f5e753340324e7c4941ab057fd9376171c0a Mon Sep 17 00:00:00 2001 From: AvtoBBus <113329450+AvtoBBus@users.noreply.github.com> Date: Fri, 6 Mar 2026 10:39:25 +0400 Subject: [PATCH 3/3] fix ServicesDefaults --- CloudDevelopment.sln | 14 +-- .../CompanyEmployees.AppHost.csproj | 2 +- .../CompanyEmployees.Generator.csproj | 3 +- .../CompanyEmployees.ServiceDefaults.csproj | 28 +++++ .../Extensions.cs | 104 ++++++++++++++++++ 5 files changed, 141 insertions(+), 10 deletions(-) create mode 100644 CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj create mode 100644 CompanyEmployees.ServiceDefaults/Extensions.cs diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cf6c038..ec784b5 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -9,7 +9,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.AppHost", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.Generator", "CompanyEmployees.Generator\CompanyEmployees.Generator.csproj", "{418E6A76-7DE1-04F1-F18A-9A7C9ED44857}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.ServiceDefaults", "AspireApp1\AspireApp1.ServiceDefaults\CompanyEmployees.ServiceDefaults.csproj", "{F9222B91-99B7-2420-265D-E51F0CE78C78}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.ServiceDefaults", "CompanyEmployees.ServiceDefaults\CompanyEmployees.ServiceDefaults.csproj", "{53C4EDF4-E3C2-A484-171F-78A5FD7190F6}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -36,12 +36,12 @@ Global {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Debug|Any CPU.Build.0 = Debug|Any CPU {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Release|Any CPU.ActiveCfg = Release|Any CPU {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Release|Any CPU.Build.0 = Release|Any CPU - {F9222B91-99B7-2420-265D-E51F0CE78C78}.123|Any CPU.ActiveCfg = Debug|Any CPU - {F9222B91-99B7-2420-265D-E51F0CE78C78}.123|Any CPU.Build.0 = Debug|Any CPU - {F9222B91-99B7-2420-265D-E51F0CE78C78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F9222B91-99B7-2420-265D-E51F0CE78C78}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F9222B91-99B7-2420-265D-E51F0CE78C78}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F9222B91-99B7-2420-265D-E51F0CE78C78}.Release|Any CPU.Build.0 = Release|Any CPU + {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.123|Any CPU.ActiveCfg = 123|Any CPU + {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.123|Any CPU.Build.0 = 123|Any CPU + {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj b/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj index 7e140d3..dd87fa5 100644 --- a/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj +++ b/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj @@ -16,9 +16,9 @@
- + diff --git a/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj b/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj index 114d0c4..b0d3ba2 100644 --- a/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj +++ b/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj @@ -10,11 +10,10 @@ - - + diff --git a/CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj b/CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj new file mode 100644 index 0000000..4e142da --- /dev/null +++ b/CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + enable + enable + true + Debug;Release;123 + + + + + + + + + + + + + + + + + + + + diff --git a/CompanyEmployees.ServiceDefaults/Extensions.cs b/CompanyEmployees.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..f1836a6 --- /dev/null +++ b/CompanyEmployees.ServiceDefaults/Extensions.cs @@ -0,0 +1,104 @@ +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; +using Serilog; + +namespace CompanyEmployees.ServiceDefaults; + +public static class Extensions +{ + public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) + { + builder.ConfigureSerilog(); + builder.ConfigureOpenTelemetry(); + builder.AddDefaultHealthChecks(); + builder.Services.AddServiceDiscovery(); + builder.Services.ConfigureHttpClientDefaults(http => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + return builder; + } + + public static IHostApplicationBuilder ConfigureSerilog(this IHostApplicationBuilder builder) + { + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(builder.Configuration) + .Enrich.FromLogContext() + .Enrich.WithEnvironmentName() + .Enrich.WithThreadId() + .Enrich.WithMachineName() + .WriteTo.Console(outputTemplate: + "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}") + .CreateLogger(); + + builder.Services.AddSerilog(); + + return builder; + } + + public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder) + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + return builder; + } + + public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder) + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + app.MapHealthChecks("/health"); + app.MapHealthChecks("/alive", new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + + return app; + } +} \ No newline at end of file