-
Notifications
You must be signed in to change notification settings - Fork 51
Вольгов Даниил Лаб. 1 Группа 6513 #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
the80hz
wants to merge
32
commits into
itsecd:main
Choose a base branch
from
the80hz:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
7cec63d
Ignores macOS .DS_Store files
the80hz 1ef5a12
Лаб 1: добавлен сервис генерации учебных курсов на Bogus
the80hz bb86231
Лаб 1: добавлено кэширование генерации через Redis
the80hz e568e91
Лаб 1: добавлено структурное логирование генератора и кэша
the80hz b0910cf
Лаб 1: настроена оркестрация через .NET Aspire и Redis
the80hz c280b1f
Лаб 1: зависимости приведены к .NET 8 и backend запущен
the80hz b8261c4
Лаб 1: исправлен запуск оркестрации Aspire AppHost
the80hz 34c232f
Лаб 1: добавлена поддержка внешних HTTP-эндпоинтов для генератора курсов
the80hz 58a6d82
Лаб 1: добавлен Makefile для управления проектом и контейнером Redis
the80hz 946e793
Лаб 1: добавлено использование патронимиков для генерации полных имен…
the80hz b74aa51
Лаб 1: обновлены данные в компоненте StudentCard и настроен BaseAddre…
the80hz 5457b0f
Лаб 1: переименован словарь патронимов и добавлена поддержка женских …
the80hz d526502
Лаб 1: добавлена настройка окружения для проекта course-generator-api
the80hz 22e1d0d
Лаб 1: подключены ServiceDefaults и health-эндпоинты в CourseGenerato…
the80hz 084a517
Лаб 1: расширены ServiceDefaults (telemetry, discovery, resilience)
the80hz e0020ea
Лаб 1: обновлен AppHost до Aspire 9.5 с WaitFor и RedisInsight
the80hz 9e1a396
Лаб 1: добавлен Client.Wasm в оркестрацию AppHost
the80hz 6df7844
Лаб 1: добавлены контроллер, DTO и интерфейсы для генератора курсов
the80hz 80b42cc
Лаб 1: добавлены ссылки на проекты Client.Wasm и CourseGenerator.Api …
the80hz 4276483
Лаб 1: убран бесполезный для браузерного клиента вызов
the80hz f88c6d8
Лаб 1: убран вызов WithHttpEndpoint для courseGeneratorApi
the80hz 9d8256a
Лаб1: добавил саммари из замечаний pr
the80hz 1f9789b
Лаб 1: дополнительные саммари
the80hz dab62d2
Лаб 1: обновлен параметр генерации контрактов и удалён класс CourseGe…
the80hz e82b1a3
Лаб 1: добавлено ограничение на параметр count в методе GenerateAsync
the80hz 0339ec7
Лаб 1: переделал генерацию под RuleFor()
the80hz ffda91f
Лаб 1: обновлён способ подключения к Redis, заменён на AddRedisDistri…
the80hz 495593c
Лаб 1: фейкер вынесен в статическое поле
the80hz 192f34b
Лаб 1: удалены настройки подключения к Redis из appsettings.json
the80hz c5b3106
Лаб1: добавлен метод получения контракта по идентификатору
the80hz 14b1a6d
Лаб 1: указан порт для апи
the80hz 67bf219
Лаб 1: поправлен генератор объектов
the80hz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -416,3 +416,6 @@ FodyWeavers.xsd | |
| *.msix | ||
| *.msm | ||
| *.msp | ||
|
|
||
| # User-specific | ||
| .DS_Store | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "http://localhost:5117/api/courses/by-id" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <Sdk Name="Aspire.AppHost.Sdk" Version="9.5.0" /> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| <IsAspireHost>true</IsAspireHost> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.0" /> | ||
| <PackageReference Include="Aspire.Hosting.Redis" Version="9.5.0" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" /> | ||
| <ProjectReference Include="..\CourseGenerator.Api\CourseGenerator.Api.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| var builder = DistributedApplication.CreateBuilder(args); | ||
|
|
||
| var redis = builder.AddRedis("redis") | ||
| .WithRedisInsight(containerName: "redis-insight"); | ||
|
|
||
| var courseGeneratorApi = builder.AddProject<Projects.CourseGenerator_Api>("course-generator-api") | ||
| .WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development") | ||
| .WithReference(redis) | ||
| .WaitFor(redis) | ||
| .WithHttpEndpoint(name: "api", port: 5117); | ||
|
|
||
| builder.AddProject<Projects.Client_Wasm>("client-wasm") | ||
| .WaitFor(courseGeneratorApi) | ||
| .WithExternalHttpEndpoints(); | ||
|
|
||
| builder.Build().Run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| { | ||
| "$schema": "https://json.schemastore.org/launchsettings.json", | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "applicationUrl": "http://localhost:15044", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development", | ||
| "DOTNET_ENVIRONMENT": "Development", | ||
| "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true", | ||
| "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19078", | ||
| "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20218" | ||
| } | ||
| } | ||
| } | ||
| } |
21 changes: 21 additions & 0 deletions
21
CloudDevelopment.ServiceDefaults/CloudDevelopment.ServiceDefaults.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| <IsAspireSharedProject>true</IsAspireSharedProject> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <FrameworkReference Include="Microsoft.AspNetCore.App" /> | ||
| <PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.9.0" /> | ||
| <PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.5.0" /> | ||
| <PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" /> | ||
| <PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" /> | ||
| <PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" /> | ||
| <PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" /> | ||
| <PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| 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 Microsoft.Extensions.Hosting; | ||
|
|
||
| public static class Extensions | ||
| { | ||
| private const string HealthEndpointPath = "/health"; | ||
| private const string AlivenessEndpointPath = "/alive"; | ||
|
|
||
| public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder | ||
| { | ||
| builder.ConfigureOpenTelemetry(); | ||
|
|
||
| builder.AddDefaultHealthChecks(); | ||
|
|
||
| builder.Services.AddServiceDiscovery(); | ||
|
|
||
| builder.Services.ConfigureHttpClientDefaults(http => | ||
| { | ||
| http.AddStandardResilienceHandler(); | ||
| http.AddServiceDiscovery(); | ||
| }); | ||
|
|
||
| return builder; | ||
| } | ||
|
|
||
| public static TBuilder ConfigureOpenTelemetry<TBuilder>(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 => | ||
| tracing.Filter = context => | ||
| !context.Request.Path.StartsWithSegments(HealthEndpointPath) | ||
| && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) | ||
| ) | ||
| .AddHttpClientInstrumentation(); | ||
| }); | ||
|
|
||
| builder.AddOpenTelemetryExporters(); | ||
|
|
||
| return builder; | ||
| } | ||
|
|
||
| private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builder) | ||
| where TBuilder : IHostApplicationBuilder | ||
| { | ||
| var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); | ||
|
|
||
| if (useOtlpExporter) | ||
| { | ||
| builder.Services.AddOpenTelemetry().UseOtlpExporter(); | ||
| } | ||
|
|
||
| return builder; | ||
| } | ||
|
|
||
| public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) | ||
| where TBuilder : IHostApplicationBuilder | ||
| { | ||
| builder.Services.AddHealthChecks() | ||
| .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); | ||
|
|
||
| return builder; | ||
| } | ||
|
|
||
| public static WebApplication MapDefaultEndpoints(this WebApplication app) | ||
| { | ||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.MapHealthChecks(HealthEndpointPath); | ||
| app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions | ||
| { | ||
| Predicate = healthCheck => healthCheck.Tags.Contains("live") | ||
| }); | ||
| } | ||
|
|
||
| return app; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
CourseGenerator.Api/Controllers/CourseContractsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| using System.ComponentModel.DataAnnotations; | ||
| using CourseGenerator.Api.Dto; | ||
| using CourseGenerator.Api.Interfaces; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace CourseGenerator.Api.Controllers; | ||
|
|
||
| [ApiController] | ||
| [Route("api/courses")] | ||
| public sealed class CourseContractsController( | ||
| ICourseContractsService contractsService, | ||
| ICourseContractGenerator contractGenerator) : ControllerBase | ||
| { | ||
| /// <summary> | ||
| /// Генерирует список контрактов курсов с кэшированием результата в Redis. | ||
| /// </summary> | ||
| /// <param name="count">Количество контрактов для генерации (от 1 до 100).</param> | ||
| /// <param name="cancellationToken">Токен отмены запроса.</param> | ||
| /// <returns>Список сгенерированных контрактов курсов.</returns> | ||
| /// <response code="200">Контракты успешно получены.</response> | ||
| /// <response code="400">Передан недопустимый параметр count.</response> | ||
| [HttpGet("generate")] | ||
| [ProducesResponseType(typeof(IReadOnlyList<CourseContractDto>), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| public async Task<ActionResult<IReadOnlyList<CourseContractDto>>> GenerateAsync( | ||
| [FromQuery, Range(1, 100)] int count, | ||
| CancellationToken cancellationToken) | ||
|
Comment on lines
+22
to
+27
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Функционал не соответствует заданию
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не совсем понял, какой именно пункт задания не выполнен в этом месте |
||
| { | ||
| try | ||
| { | ||
| var contracts = await contractsService.GenerateAsync(count, cancellationToken); | ||
| var dto = contracts | ||
| .Select(contract => new CourseContractDto( | ||
| contract.Id, | ||
| contract.CourseName, | ||
| contract.TeacherFullName, | ||
| contract.StartDate, | ||
| contract.EndDate, | ||
| contract.MaxStudents, | ||
| contract.CurrentStudents, | ||
| contract.HasCertificate, | ||
| contract.Price, | ||
| contract.Rating)) | ||
| .ToList(); | ||
|
|
||
| return Ok(dto); | ||
| } | ||
| catch (ArgumentOutOfRangeException ex) | ||
| { | ||
| var problem = new ValidationProblemDetails(new Dictionary<string, string[]> | ||
| { | ||
| ["count"] = [ex.Message] | ||
| }); | ||
| return BadRequest(problem); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Возвращает один сгенерированный контракт по идентификатору для совместимости с клиентом. | ||
| /// </summary> | ||
| /// <param name="id">Неотрицательный идентификатор объекта.</param> | ||
| /// <param name="cancellationToken">Токен отмены запроса.</param> | ||
| /// <returns>Сгенерированный контракт.</returns> | ||
| /// <response code="200">Контракт успешно получен.</response> | ||
| /// <response code="400">Передан недопустимый параметр id.</response> | ||
| [HttpGet("by-id")] | ||
| [ProducesResponseType(typeof(CourseContractDto), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| public ActionResult<CourseContractDto> GetByIdAsync( | ||
| [FromQuery, Range(0, int.MaxValue)] int id, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| var contract = contractGenerator.GenerateById(id); | ||
|
|
||
| return Ok(new CourseContractDto( | ||
| contract.Id, | ||
| contract.CourseName, | ||
| contract.TeacherFullName, | ||
| contract.StartDate, | ||
| contract.EndDate, | ||
| contract.MaxStudents, | ||
| contract.CurrentStudents, | ||
| contract.HasCertificate, | ||
| contract.Price, | ||
| contract.Rating)); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
| <NoWarn>$(NoWarn);1591</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.5.2" /> | ||
| <PackageReference Include="Bogus" Version="35.6.1" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| namespace CourseGenerator.Api.Dto; | ||
|
|
||
| /// <summary> | ||
| /// Контракт на проведение учебного курса. | ||
| /// </summary> | ||
| public sealed record CourseContractDto( | ||
| int Id, | ||
| string CourseName, | ||
| string TeacherFullName, | ||
| DateOnly StartDate, | ||
| DateOnly EndDate, | ||
| int MaxStudents, | ||
| int CurrentStudents, | ||
| bool HasCertificate, | ||
| decimal Price, | ||
| int Rating); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.