diff --git a/Aspire/Aspire.AppHost/AppHost.cs b/Aspire/Aspire.AppHost/AppHost.cs new file mode 100644 index 0000000..aa03cfc --- /dev/null +++ b/Aspire/Aspire.AppHost/AppHost.cs @@ -0,0 +1,13 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var cache = builder.AddRedis("programproj-cache").WithRedisInsight(containerName: "programproj-insight"); + +var apiService = builder.AddProject("programproj-api") + .WithReference(cache) + .WithHttpHealthCheck("/health") + .WaitFor(cache); + +builder.AddProject("programproj-wasm") + .WaitFor(apiService); + +builder.Build().Run(); diff --git a/Aspire/Aspire.AppHost/Aspire.AppHost.csproj b/Aspire/Aspire.AppHost/Aspire.AppHost.csproj new file mode 100644 index 0000000..0f00fac --- /dev/null +++ b/Aspire/Aspire.AppHost/Aspire.AppHost.csproj @@ -0,0 +1,23 @@ + + + + + + Exe + net8.0 + enable + enable + 348a6352-668a-4b0d-833f-bbd1cc51ceb3 + + + + + + + + + + + + + diff --git a/Aspire/Aspire.AppHost/Properties/launchSettings.json b/Aspire/Aspire.AppHost/Properties/launchSettings.json new file mode 100644 index 0000000..59a529e --- /dev/null +++ b/Aspire/Aspire.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:17161;http://localhost:15041", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21204", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22223" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15041", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19104", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20068" + } + } + } +} diff --git a/Aspire/Aspire.AppHost/appsettings.Development.json b/Aspire/Aspire.AppHost/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Aspire/Aspire.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Aspire/Aspire.AppHost/appsettings.json b/Aspire/Aspire.AppHost/appsettings.json new file mode 100644 index 0000000..31c092a --- /dev/null +++ b/Aspire/Aspire.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj b/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj new file mode 100644 index 0000000..1b6e209 --- /dev/null +++ b/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj @@ -0,0 +1,22 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + diff --git a/Aspire/Aspire.ServiceDefaults/Extensions.cs b/Aspire/Aspire.ServiceDefaults/Extensions.cs new file mode 100644 index 0000000..b72c875 --- /dev/null +++ b/Aspire/Aspire.ServiceDefaults/Extensions.cs @@ -0,0 +1,127 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.ServiceDiscovery; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace Microsoft.Extensions.Hosting; + +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// This project should be referenced by each service project in your solution. +// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + + builder.AddDefaultHealthChecks(); + + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + // Turn on resilience by default + http.AddStandardResilienceHandler(); + + // Turn on service discovery by default + http.AddServiceDiscovery(); + }); + + // Uncomment the following to restrict the allowed schemes for service discovery. + // builder.Services.Configure(options => + // { + // options.AllowedSchemes = ["https"]; + // }); + + return builder; + } + + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(tracing => + // Exclude health check requests from tracing + tracing.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) + && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) + ) + // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) + //.AddGrpcClientInstrumentation() + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry().UseOtlpExporter(); + } + + // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) + //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) + //{ + // builder.Services.AddOpenTelemetry() + // .UseAzureMonitor(); + //} + + return builder; + } + + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + // Add a default liveness check to ensure app is responsive + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + // Adding health checks endpoints to applications in non-development environments has security implications. + // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. + if (app.Environment.IsDevelopment()) + { + // All health checks must pass for app to be considered ready to accept traffic after starting + app.MapHealthChecks(HealthEndpointPath); + + // Only health checks tagged with the "live" tag must pass for app to be considered alive + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f118..2093dbc 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,9 +4,9 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ + Номер №1 "Кэширование" + Вариант №42 "Программный проект" + Выполнена Кадников Николай 6513 Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 4dda7c0..118aaa1 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7170/land-plot" + "BaseAddress": "https://localhost:7262/program-proj" } \ No newline at end of file diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241..4b6a66b 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}") = "Service.Api", "Service.Api\Service.Api.csproj", "{5003CEA3-9343-45C1-B1E4-6FE43745A8D5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.AppHost", "Aspire\Aspire.AppHost\Aspire.AppHost.csproj", "{466A15CD-2DE0-4374-9653-08989D32708A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.ServiceDefaults", "Aspire\Aspire.ServiceDefaults\Aspire.ServiceDefaults.csproj", "{AD6B47E3-6C6E-420E-9803-369B1474B73F}" +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 + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5003CEA3-9343-45C1-B1E4-6FE43745A8D5}.Release|Any CPU.Build.0 = Release|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {466A15CD-2DE0-4374-9653-08989D32708A}.Release|Any CPU.Build.0 = Release|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD6B47E3-6C6E-420E-9803-369B1474B73F}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Service.Api/Entity/ProgramProject.cs b/Service.Api/Entity/ProgramProject.cs new file mode 100644 index 0000000..71594ab --- /dev/null +++ b/Service.Api/Entity/ProgramProject.cs @@ -0,0 +1,15 @@ +namespace Service.Api.Entity; + +public record ProgramProject +{ + public int Id { get; init; } + public string Name { get; set; } + public string Customer { get; set; } + public string Manager { get; set; } + public DateOnly StartDate { get; set; } + public DateOnly EndDatePlanned { get; set; } + public DateOnly? EndDateReal { get; set; } + public decimal Budget { get; set; } + public decimal SpentMoney { get; set; } + public int FinishedPerCent { get; set; } +} diff --git a/Service.Api/Generator/ProgramProjectFaker.cs b/Service.Api/Generator/ProgramProjectFaker.cs new file mode 100644 index 0000000..2e9b945 --- /dev/null +++ b/Service.Api/Generator/ProgramProjectFaker.cs @@ -0,0 +1,28 @@ +using Bogus; +using Service.Api.Entity; + +namespace Service.Api.Generator; + +public class ProgramProjectFaker : Faker +{ + public ProgramProjectFaker() : base("ru") + { + RuleFor(o => o.Name, f => f.Commerce.ProductName()); + RuleFor(o => o.Customer, f => f.Company.CompanyName()); + RuleFor(o => o.Manager, f => f.Name.FullName()); + RuleFor(o => o.StartDate, f => DateOnly.FromDateTime(f.Date.Past(2, DateTime.Now))); + RuleFor(o => o.EndDatePlanned, (f, o) => DateOnly.FromDateTime(f.Date.Future(5, o.StartDate.ToDateTime(TimeOnly.MinValue)))); + RuleFor(o => o.EndDateReal, (f, o) => + { + DateTime end = f.Date.Between(o.StartDate.ToDateTime(TimeOnly.MinValue), o.EndDatePlanned.ToDateTime(TimeOnly.MinValue)); + return end > DateTime.Now ? null : DateOnly.FromDateTime(end); + }); + RuleFor(o => o.Budget, f => Math.Round(f.Finance.Amount(100_000, 1_000_000), 2)); + RuleFor(o => o.FinishedPerCent, (f, o) => o.EndDateReal != null ? 100 : f.Random.Number(1, 100)); + RuleFor(o => o.SpentMoney, (f, o) => + { + var spread = Convert.ToInt32(o.Budget) / 15; + return Math.Round((o.Budget - f.Finance.Amount(-spread, spread)) * o.FinishedPerCent / 100, 2); + }); + } +} diff --git a/Service.Api/Generator/ProgramProjectGeneratorService.cs b/Service.Api/Generator/ProgramProjectGeneratorService.cs new file mode 100644 index 0000000..a843201 --- /dev/null +++ b/Service.Api/Generator/ProgramProjectGeneratorService.cs @@ -0,0 +1,16 @@ +using Bogus; +using Service.Api.Entity; + +namespace Service.Api.Generator; + +public class ProgramProjectGeneratorService(Faker faker) +{ + private Faker _faker = faker; + + public ProgramProject GetProgramProjectInstance(int id) + { + ProgramProject programProject = _faker.Generate(); + return programProject with { Id = id }; + + } +} diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs new file mode 100644 index 0000000..3883a3b --- /dev/null +++ b/Service.Api/Program.cs @@ -0,0 +1,64 @@ +using Bogus; +using Service.Api.Entity; +using Service.Api.Generator; +using Service.Api.Redis; +using StackExchange.Redis; + +var builder = WebApplication.CreateBuilder(args); + +builder.AddServiceDefaults(); + +// Add services to the container. +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + + +builder.Services.AddSingleton, ProgramProjectFaker>(); +builder.Services.AddSingleton(); + +builder.Services.AddSingleton(sp => +{ + var configuration = builder.Configuration.GetConnectionString("programproj-cache"); + if (configuration != null) return ConnectionMultiplexer.Connect(configuration); + else throw new InvalidOperationException("u should fix the redis connection"); +}); + +builder.Services.AddScoped(); + +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + policy.AllowAnyOrigin() + .AllowAnyHeader() + .AllowAnyMethod()); +}); + +var app = builder.Build(); + +app.UseCors(); + +app.MapDefaultEndpoints(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.MapGet("/program-proj", async (int id, ProgramProjectGeneratorService generatorService, RedisCacheService cs) => +{ + var key = $"project:{id}"; + var programProject = await cs.GetAsync(key); + if(programProject != null) return Results.Ok(programProject); + var newProject = generatorService.GetProgramProjectInstance(id); + await cs.SetAsync(key, newProject, TimeSpan.FromHours(12)); + return Results.Ok(newProject); +}) +.WithName("GetProgramProject") +.WithOpenApi(); + +app.Run(); diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json new file mode 100644 index 0000000..f7af466 --- /dev/null +++ b/Service.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:45188", + "sslPort": 44359 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5044", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7262;http://localhost:5044", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Service.Api/Redis/RedisCacheService.cs b/Service.Api/Redis/RedisCacheService.cs new file mode 100644 index 0000000..ce478ae --- /dev/null +++ b/Service.Api/Redis/RedisCacheService.cs @@ -0,0 +1,33 @@ +using System.Text.Json; +using Service.Api.Entity; +using StackExchange.Redis; + +namespace Service.Api.Redis; + +public class RedisCacheService +{ + private readonly IDatabase _db; + + public RedisCacheService(IConnectionMultiplexer redis) + { + this._db = redis.GetDatabase(); + } + + public async Task SetAsync(string key, T value, TimeSpan? expire) + { + var json = JsonSerializer.Serialize(value); + await this._db.StringSetAsync(key, json, expire); + } + + public async Task GetAsync(string key) + { + var value = await this._db.StringGetAsync(key); + if (value.IsNullOrEmpty) return default; + return JsonSerializer.Deserialize(value!); + } + + public async Task RemoveAsync(string key) + { + await this._db.KeyDeleteAsync(key); + } +} diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj new file mode 100644 index 0000000..bc64433 --- /dev/null +++ b/Service.Api/Service.Api.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/Service.Api/Service.Api.http b/Service.Api/Service.Api.http new file mode 100644 index 0000000..2eec3c2 --- /dev/null +++ b/Service.Api/Service.Api.http @@ -0,0 +1,6 @@ +@Service.Api_HostAddress = https://localhost:7262 + +GET {{Service.Api_HostAddress}}/program-proj?id=1 +Accept: application/json + +### diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Service.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/Service.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}