-
Notifications
You must be signed in to change notification settings - Fork 50
Балдин Никита Лаб. 1 Группа 6511 #79
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
Closed
Closed
Changes from all commits
Commits
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
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": "https://localhost:7208/api/vehicle" | ||
| } | ||
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 |
|---|---|---|
| @@ -1,128 +1,49 @@ | ||
| # Современные технологии разработки программного обеспечения | ||
| [Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) | ||
| # Лабораторная работа №1 — «Кэширование» | ||
|
|
||
| ## Задание | ||
| ### Цель | ||
| Реализация проекта микросервисного бекенда. | ||
| **Вариант:** №1 — Транспортное средство | ||
|
|
||
| ### Задачи | ||
| * Реализация межсервисной коммуникации, | ||
| * Изучение работы с брокерами сообщений, | ||
| * Изучение архитектурных паттернов, | ||
| * Изучение работы со средствами оркестрации на примере .NET Aspire, | ||
| * Повторение основ работы с системами контроля версий, | ||
| * Интеграционное тестирование. | ||
| --- | ||
|
|
||
| ### Лабораторные работы | ||
| <details> | ||
| <summary>1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов</summary> | ||
| <br> | ||
|
|
||
| В рамках первой лабораторной работы необходимо: | ||
| * Реализовать сервис генерации контрактов на основе Bogus, | ||
| * Реализовать кеширование при помощи IDistributedCache и Redis, | ||
| * Реализовать структурное логирование сервиса генерации, | ||
| * Настроить оркестрацию Aspire. | ||
|
|
||
| </details> | ||
| <details> | ||
| <summary>2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы</summary> | ||
| <br> | ||
|
|
||
| В рамках второй лабораторной работы необходимо: | ||
| * Настроить оркестрацию на запуск нескольких реплик сервиса генерации, | ||
| * Реализовать апи гейтвей на основе Ocelot, | ||
| * Имплементировать алгоритм балансировки нагрузки согласно варианту. | ||
| ## Цель работы | ||
|
|
||
| <br> | ||
| </details> | ||
| <details> | ||
| <summary>3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда</summary> | ||
| <br> | ||
| Реализовать сервис генерации данных о транспортных средствах с кэшированием ответов при помощи Redis и структурным логированием. | ||
|
|
||
| В рамках третьей лабораторной работы необходимо: | ||
| * Добавить в оркестрацию объектное хранилище, | ||
| * Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, | ||
| * Реализовать отправку генерируемых данных в файловый сервис посредством брокера, | ||
| * Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. | ||
| --- | ||
|
|
||
| <br> | ||
| </details> | ||
| <details> | ||
| <summary>4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud</summary> | ||
| <br> | ||
|
|
||
| В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: | ||
| * Клиент - в хостинг через отдельный бакет Object Storage, | ||
| * Сервис генерации - в Cloud Function, | ||
| * Апи гейтвей - в Serverless Integration как API Gateway, | ||
| * Брокер сообщений - в Message Queue, | ||
| * Файловый сервис - в Cloud Function, | ||
| * Объектное хранилище - в отдельный бакет Object Storage, | ||
| ## Стек технологий | ||
|
|
||
| <br> | ||
| </details> | ||
| | Компонент | Технология | | ||
| |---|---| | ||
| | Серверная часть | ASP.NET Core Web API (.NET 8) | | ||
| | Генерация данных | Bogus 35.6.5 | | ||
| | Кэширование | IDistributedCache + Redis (Aspire) | | ||
| | Логирование | Microsoft.Extensions.Logging (структурное) | | ||
| | Оркестрация | .NET Aspire 9.5.2 | | ||
| | Клиент | Blazor WebAssembly (.NET 8) | | ||
|
|
||
| ## Задание. Общая часть | ||
| **Обязательно**: | ||
| * Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). | ||
| * Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). | ||
| * Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). | ||
| * Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). | ||
| * Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. | ||
| --- | ||
|
|
||
| **Факультативно**: | ||
| * Перенос бекенда на облачную инфраструктуру Yandex Cloud | ||
| ## Модель данных — Транспортное средство | ||
|
|
||
| Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. | ||
| Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. | ||
| | # | Название | Тип | Источник (Bogus) | Ограничение | | ||
| |---|---|---|---|---| | ||
| | 1 | Идентификатор в системе | `int` | параметр запроса | — | | ||
| | 2 | VIN-номер | `string` | `Vehicle.Vin()` | — | | ||
| | 3 | Производитель | `string` | `Vehicle.Manufacturer()` | — | | ||
| | 4 | Модель | `string` | `Vehicle.Model()` | — | | ||
| | 5 | Год выпуска | `int` | `Date.Past(30).Year` | ≤ текущий год | | ||
| | 6 | Тип корпуса | `string` | `Vehicle.Type()` | — | | ||
| | 7 | Тип топлива | `string` | `Vehicle.Fuel()` | — | | ||
| | 8 | Цвет корпуса | `string` | `Commerce.Color()` | — | | ||
| | 9 | Пробег | `double` | `Random.Double(0, 500_000)` | ≥ 0 | | ||
| | 10 | Дата последнего техобслуживания | `DateOnly` | `Date.Between(...)` | ≥ год выпуска | | ||
|
|
||
| По итогу работы в семестре должна получиться следующая информационная система: | ||
| <details> | ||
| <summary>C4 диаграмма</summary> | ||
| <img width="1584" height="771" alt="Современные_технологии_разработки_ПО_drawio" src="https://github.com/user-attachments/assets/71d6356f-7eb4-463d-b9f3-c953e5312993" /> | ||
| </details> | ||
| --- | ||
|
|
||
| ## Варианты заданий | ||
| Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. | ||
| ## API | ||
|
|
||
| [Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) | ||
| [Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) | ||
|
|
||
| ## Схема сдачи | ||
|
|
||
| На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). | ||
|
|
||
| Общая схема: | ||
| 1. Сделать форк данного репозитория | ||
| 2. Выполнить задание | ||
| 3. Сделать PR в данный репозиторий | ||
| 4. Исправить замечания после code review | ||
| 5. Получить approve | ||
|
|
||
| ## Критерии оценивания | ||
|
|
||
| Конкурентный принцип. | ||
| Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: | ||
| 1. Скорость разработки | ||
| 2. Качество разработки | ||
| 3. Полнота выполнения задания | ||
|
|
||
| Быстрее делаете PR - у вас преимущество. | ||
| Быстрее получаете Approve - у вас преимущество. | ||
| Выполните нечто немного выходящее за рамки проекта - у вас преимущество. | ||
| Не укладываетесь в дедлайн - получаете минимально возможный балл. | ||
|
|
||
| ### Шкала оценивания | ||
|
|
||
| - **3 балла** за качество кода, из них: | ||
| - 2 балла - базовая оценка | ||
| - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: | ||
| - Реализация факультативного функционала | ||
| - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл | ||
|
|
||
| ## Вопросы и обратная связь по курсу | ||
|
|
||
| Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). | ||
| Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). | ||
| ### `GET /api/vehicle?id={id}` | ||
|
|
||
| Возвращает транспортное средство по идентификатору. | ||
| При первом запросе — генерирует и сохраняет в кэш. | ||
| При повторном запросе — возвращает из кэша (TTL 15 минут). |
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,34 @@ | ||
| using Bogus; | ||
| using VehicleApp.Api.Models; | ||
|
|
||
| namespace VehicleApp.Api.Generators; | ||
|
|
||
| /// <summary> | ||
| /// Генератор транспортных средств | ||
| /// </summary> | ||
| public static class VehicleGenerator | ||
| { | ||
| private static readonly Faker<Vehicle> _faker = new Faker<Vehicle>() | ||
| .RuleFor(v => v.Vin, f => f.Vehicle.Vin()) | ||
| .RuleFor(v => v.Manufacturer, f => f.Vehicle.Manufacturer()) | ||
| .RuleFor(v => v.Model, f => f.Vehicle.Model()) | ||
| .RuleFor(v => v.Year, f => f.Date.Past(30).Year) | ||
| .RuleFor(v => v.BodyType, f => f.Vehicle.Type()) | ||
| .RuleFor(v => v.FuelType, f => f.Vehicle.Fuel()) | ||
| .RuleFor(v => v.BodyColor, f => f.Commerce.Color()) | ||
| .RuleFor(v => v.Mileage, f => Math.Round(f.Random.Double(0, 500_000), 1)) | ||
| .RuleFor(v => v.LastMaintenanceDate, (f, v) => | ||
| DateOnly.FromDateTime(f.Date.Between(new DateTime(v.Year, 1, 1), DateTime.UtcNow))); | ||
|
|
||
| /// <summary> | ||
| /// Сгенерировать транспортное средство по идентификатору | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор транспортного средства</param> | ||
| /// <returns>Сгенерированное транспортное средство</returns> | ||
| public static Vehicle Generate(int id) | ||
| { | ||
| var vehicle = _faker.Generate(); | ||
| vehicle.Id = id; | ||
| return vehicle; | ||
| } | ||
| } |
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,57 @@ | ||
| namespace VehicleApp.Api.Models; | ||
|
|
||
| /// <summary> | ||
| /// Транспортное средство | ||
| /// </summary> | ||
| public sealed class Vehicle | ||
| { | ||
| /// <summary> | ||
| /// Идентификатор в системе | ||
| /// </summary> | ||
| public int Id { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// VIN-номер | ||
| /// </summary> | ||
| public required string Vin { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Производитель | ||
| /// </summary> | ||
| public required string Manufacturer { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Модель | ||
| /// </summary> | ||
| public required string Model { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Год выпуска | ||
| /// </summary> | ||
| public int Year { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Тип корпуса | ||
| /// </summary> | ||
| public required string BodyType { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Тип топлива | ||
| /// </summary> | ||
| public required string FuelType { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Цвет корпуса | ||
| /// </summary> | ||
| public required string BodyColor { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Пробег | ||
| /// </summary> | ||
| public double Mileage { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Дата последнего техобслуживания | ||
| /// </summary> | ||
| public DateOnly LastMaintenanceDate { get; init; } | ||
| } |
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,29 @@ | ||
| using VehicleApp.Api.Services; | ||
| using VehicleApp.ServiceDefaults; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| builder.AddServiceDefaults(); | ||
| builder.AddRedisDistributedCache("cache"); | ||
|
|
||
| builder.Services.AddScoped<IVehicleService, VehicleService>(); | ||
|
|
||
| var allowedOrigins = builder.Configuration | ||
| .GetSection("Cors:AllowedOrigins") | ||
| .Get<string[]>() ?? []; | ||
|
|
||
| builder.Services.AddCors(options => | ||
| options.AddDefaultPolicy(policy => | ||
| policy.WithOrigins(allowedOrigins) | ||
| .WithMethods("GET") | ||
| .WithHeaders("Content-Type"))); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| app.MapDefaultEndpoints(); | ||
| app.UseCors(); | ||
|
|
||
| app.MapGet("/api/vehicle", async (int id, IVehicleService service) => | ||
| Results.Ok(await service.GetOrGenerateAsync(id))); | ||
|
|
||
| app.Run(); |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Опечатка