diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..e86fb27 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 d1fe7ab..5f43a0a 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 cb48241..0956a72 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 0000000..5988981 --- /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 0000000..bbe1452 --- /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 0000000..4fac06b --- /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 0000000..0c208ae --- /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 0000000..31c092a --- /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 0000000..c77f42f --- /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 0000000..1cf0bee --- /dev/null +++ b/CompanyEmployee.Generator/Controller/CompanyEmployeeController.cs @@ -0,0 +1,41 @@ +using CompanyEmployee.Generator.Dto; +using CompanyEmployee.Generator.Service; +using Microsoft.AspNetCore.Mvc; + +namespace CompanyEmployee.Generator.Controller; + +/// +/// Контроллер для получения сотрудника компании по id +/// +/// Сервис получения сотрудника компании +/// Логгер +[ApiController] +[Route("company-employee")] +public class CompanyEmployeeController( + ICompanyEmployeeService service, + ILogger logger + ) : ControllerBase +{ + /// + /// Метод для получения сотрудника компании по id + /// + /// Идентификатор сотрудника + /// Токен отмены запроса + /// DTO сотрудника компании + /// Успешное получение сотрудника + /// Некорректный id + [HttpGet] + [ProducesResponseType(typeof(CompanyEmployeeDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] + 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: {employeeId}", id); + + 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 0000000..51192f9 --- /dev/null +++ b/CompanyEmployee.Generator/Dto/CompanyEmployeeDto.cs @@ -0,0 +1,57 @@ +namespace CompanyEmployee.Generator.Dto; + +/// +/// Информация о сотруднике компании +/// +public class CompanyEmployeeDto +{ + /// + /// Идентификатор сотрудника в системе + /// + public required int Id { get; init; } + + /// + /// ФИО + /// + public required string FullName { get; init; } + + /// + /// Должность + /// + public required string Position { get; init; } + + /// + /// Отдел + /// + public required string Department { get; init; } + + /// + /// Дата приема + /// + public required DateOnly EmploymentDate { get; init; } + + /// + /// Оклад + /// + public required decimal Salary { get; init; } + + /// + /// Электронная почта + /// + public required string Email { get; init; } + + /// + /// Номер телефона + /// + public required string PhoneNumber { get; init; } + + /// + /// Индикатор увольнения + /// + public required bool DismissalFlag { get; init; } + + /// + /// Дата увольнения + /// + public DateOnly? DismissalDate { get; init; } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Program.cs b/CompanyEmployee.Generator/Program.cs new file mode 100644 index 0000000..aa5e368 --- /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.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(); +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 0000000..ea64f59 --- /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 0000000..26d8fa4 --- /dev/null +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeGenerator.cs @@ -0,0 +1,57 @@ +using Bogus; +using Bogus.DataSets; +using CompanyEmployee.Generator.Dto; + +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"]; + + public CompanyEmployeeDto Generate(int employeeId) + { + var faker = new Faker("ru") + .RuleFor(e => e.Id, _ => employeeId) + .RuleFor(e => e.FullName, f => + { + var gender = f.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray()); + + 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()) + .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.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 {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 new file mode 100644 index 0000000..22407a2 --- /dev/null +++ b/CompanyEmployee.Generator/Service/CompanyEmployeeService.cs @@ -0,0 +1,70 @@ +using System.Text.Json; +using CompanyEmployee.Generator.Dto; +using Microsoft.Extensions.Caching.Distributed; + +namespace CompanyEmployee.Generator.Service; + +/// +/// Сервис получения сотрудника компании +/// +/// Генератор сотрудника по идентификатору +/// Сервис кэширования +/// Конфигурация приложения +/// Логгер +public class CompanyEmployeeService( + ICompanyEmployeeGenerator generator, + IDistributedCache cache, + IConfiguration configuration, + ILogger logger + ) : ICompanyEmployeeService +{ + private static readonly string _companyEmployeeCachePrefix = "company-employee:"; + + private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); + + public async Task GetByIdAsync(int employeeId, CancellationToken token) + { + var cacheKey = _companyEmployeeCachePrefix + employeeId; + var cachedValue = await cache.GetStringAsync(cacheKey, token); + + CompanyEmployeeDto companyEmployee; + + if (!string.IsNullOrEmpty(cachedValue)) + { + logger.LogInformation("Read from cache, key: {cacheKey}", cacheKey); + try + { + companyEmployee = JsonSerializer.Deserialize(cachedValue, _jsonOptions); + if (companyEmployee != null) + { + return companyEmployee; + } + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error deserializing cached employee, key: {cacheKey}", cacheKey); + } + } + + companyEmployee = generator.Generate(employeeId); + + var ttlSeconds = configuration.GetValue("CompanyEmployeeCache: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}", cacheKey); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Error in caching companyEmployee, key: {cacheKey}", cacheKey); + } + + return companyEmployee; + } +} \ No newline at end of file diff --git a/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs b/CompanyEmployee.Generator/Service/ICompanyEmployeeGenerator.cs new file mode 100644 index 0000000..b2332f3 --- /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 employeeId); + +} \ 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 0000000..e165687 --- /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 employeeId, CancellationToken token); +} \ 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 0000000..cd7d0bc --- /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 0000000..e6d8e7b --- /dev/null +++ b/CompanyEmployee.Generator/appsettings.json @@ -0,0 +1,13 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CompanyEmployeeCache": { + "Enabled": true, + "TtlSeconds": 600 + }, + "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 0000000..1214e27 --- /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 0000000..0c76f9c --- /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