Compare commits

..

1 Commits

Author SHA1 Message Date
49c433bf6c Merge branch 'master' into TechMessageRework 2024-12-13 10:08:47 +05:00
178 changed files with 2194 additions and 2146 deletions

View File

@ -1,38 +0,0 @@
name: Unit tests
run-name: ${{ gitea.actor }} is testing
on: push
jobs:
test:
runs-on: ubuntu-latest
container: node
# Service containers to run with `runner-job`
services:
# Label used to access the service container
postgres:
# Docker Hub image
image: postgres
# Provide the password for postgres
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps tcp port 5432 on service container to the host
- 5442:5432
steps:
- name: Setup dotnet
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Check out repository code
uses: actions/checkout@v4
- name: Run integration tests
run: dotnet test DD.Persistence.IntegrationTests

View File

@ -1,51 +0,0 @@
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Работа с системами
/// </summary>
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class DataSourceSystemController : ControllerBase
{
private readonly IDataSourceSystemRepository dataSourceSystemRepository;
public DataSourceSystemController(IDataSourceSystemRepository dataSourceSystemRepository)
{
this.dataSourceSystemRepository = dataSourceSystemRepository;
}
/// <summary>
/// Получить системы
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult<DataSourceSystemDto>> Get(CancellationToken token)
{
var result = await dataSourceSystemRepository.Get(token);
return Ok(result);
}
/// <summary>
/// Добавить систему
/// </summary>
/// <param name="dataSourceSystemDto"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
public async Task<IActionResult> Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
await dataSourceSystemRepository.Add(dataSourceSystemDto, token);
return CreatedAtAction(nameof(Add), true);
}
}

View File

@ -1,5 +0,0 @@
{
"version": 1,
"isRoot": true,
"tools": {}
}

View File

@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>8dcdcfed-c959-4eef-9891-ae60b1b136ea</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<_WebToolingArtifacts Remove="Properties\PublishProfiles\LinuxRelease.pubxml" />
<_WebToolingArtifacts Remove="Properties\PublishProfiles\WindowsRelease.pubxml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence.API\DD.Persistence.API.csproj" />
</ItemGroup>
</Project>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<ProjectGuid>063238bf-e982-43fa-9ddb-7d7d279086d8</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ProjectGuid>063238bf-e982-43fa-9ddb-7d7d279086d8</ProjectGuid>
<SelfContained>false</SelfContained>
</PropertyGroup>
</Project>

View File

@ -1,52 +0,0 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5266"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7154;http://localhost:5266"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:54958",
"sslPort": 44352
}
}
}

View File

@ -1,29 +0,0 @@
# DD.Persistence.App Readme
## Краткое описание DD.Persistence.App сервиса
DD.Persistence.App - проект исполняемого файла микросервиса
## Настройка DD.Persistence.App (файл appsettings.json)
- `appsettings.json` - файл с настройками проекта.
### Подключение к БД
- Настройки подключения к базе хранятся в свойстве `DefaultConnection` секции `ConnectionStrings`
файла `appsettings.json`, где:
- Host - название или ip хоста;
- Database - название базы данных;
- Username - пользователь базы данных;
- Password - пароль базы данных;
- Больше информации о настройке подключения к postgreSQL можно прочесть по [ссылке](https://www.npgsql.org/doc/connection-string-parameters.html)
### Авторизация
1. В проекте предусмотрены 2 типа авторизации:
- Авторизация через KeyCloak. Используется в продакшен версии.
- Авторизация через Jwt-токен. Используется для разработки и тестирования.
2. Для включения авторизации через KeyCloak необходимо:
- Установить секцию `NeedUseKeyCloak` файла `appsettings.json` в `true`
- По необходимости настроить свойства секции `Authentication` файла `appsettings.json`
### defaultsettings.json
Копия файла `appsettings.json` хранится в файле `defaultsettings.json`

View File

@ -1,17 +0,0 @@
{
"DbConnection": {
"Host": "postgres",
"Port": 5432,
"Database": "persistence",
"Username": "postgres",
"Password": "postgres"
},
"NeedUseKeyCloak": false,
"AuthUser": {
"username": "myuser",
"password": 12345,
"clientId": "webapi",
"grantType": "password"
},
"KeycloakGetTokenUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/token"
}

View File

@ -1,25 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=persistence;Username=postgres;Password=postgres;Persist Security Info=True"
},
"AllowedHosts": "*",
"NeedUseKeyCloak": false,
"KeyCloakAuthentication": {
"Audience": "account",
"Host": "http://192.168.0.10:8321/realms/Persistence"
},
"AuthUser": {
"username": "myuser",
"password": 12345,
"clientId": "webapi",
"grantType": "password",
"http://schemas.xmlsoap.org/ws/2005/05/identity /claims/nameidentifier": "7d9f3574-6574-4ca3-845a-0276eb4aa8f6"
},
"ClientUrl": "http://localhost:5000/"
}

View File

@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"NeedUseKeyCloak": false
}

View File

@ -1,37 +0,0 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
namespace DD.Persistence.Client.Clients;
public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient
{
private readonly IRefitDataSourceSystemClient dataSourceSystemClient;
public DataSourceSystemClient(IRefitClientFactory<IRefitDataSourceSystemClient> dataSourceSystemClientFactory, ILogger<DataSourceSystemClient> logger) : base(logger)
{
this.dataSourceSystemClient = dataSourceSystemClientFactory.Create();
}
public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
await ExecutePostResponse(
async () => await dataSourceSystemClient.Add(dataSourceSystemDto, token), token);
}
public async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
{
var result = await ExecuteGetResponse(
async () => await dataSourceSystemClient.Get(token), token);
return result!;
}
public void Dispose()
{
dataSourceSystemClient.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@ -1,25 +0,0 @@
using DD.Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с системами
/// </summary>
public interface IDataSourceSystemClient : IDisposable
{
/// <summary>
/// Получить системы
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token);
/// <summary>
/// Добавить систему
/// </summary>
/// <param name="dataSourceSystemDto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
}

View File

@ -1,10 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitClient
{
}

View File

@ -1,14 +0,0 @@
using DD.Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitDataSourceSystemClient : IRefitClient, IDisposable
{
private const string BaseRoute = "/api/dataSourceSystem";
[Get($"{BaseRoute}")]
Task<IApiResponse<IEnumerable<DataSourceSystemDto>>> Get(CancellationToken token);
[Post($"{BaseRoute}")]
Task<IApiResponse> Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
}

View File

@ -1,64 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!--Генерация NuGet пакета при сборке-->
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<!--Наименование-->
<Title>DD.Persistence.Client</Title>
<!--Версия пакета-->
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<!--Версия сборки-->
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
<!--Id пакета-->
<PackageId>DD.Persistence.Client</PackageId>
<!--Автор-->
<Authors>Digital Drilling</Authors>
<!--Компания-->
<Company>Digital Drilling</Company>
<!--Описание-->
<Description>Пакет для получения клиентов для работы с Persistence сервисом</Description>
<!--Url репозитория-->
<RepositoryUrl>https://git.ddrilling.ru/on.nemtina/persistence.git</RepositoryUrl>
<!--тип репозитория-->
<RepositoryType>git</RepositoryType>
<!--Символы отладки-->
<IncludeSymbols>true</IncludeSymbols>
<!--Формат пакета с символами-->
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<!--Путь к пакету-->
<PackageOutputPath>C:\Projects\Nuget\Persistence\Client</PackageOutputPath>
<!--Readme-->
<PackageReadmeFile>Readme.md</PackageReadmeFile>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<None Include="Readme.md" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.3.0" />
<PackageReference Include="Refit" Version="8.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="9.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence.Models\DD.Persistence.Models.csproj" />
</ItemGroup>
</Project>

View File

@ -1,30 +0,0 @@
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models;
using Microsoft.Extensions.DependencyInjection;
namespace DD.Persistence.Client;
/// <summary>
///
/// </summary>
public static class DependencyInjection
{
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddPersistenceClients(this IServiceCollection services)
{
services.AddTransient(typeof(IRefitClientFactory<>), typeof(RefitClientFactory<>));
services.AddTransient<IChangeLogClient, ChangeLogClient>();
services.AddTransient<IDataSourceSystemClient, DataSourceSystemClient>();
services.AddTransient<ISetpointClient, SetpointClient>();
services.AddTransient<ITechMessagesClient, TechMessagesClient>();
services.AddTransient<ITimeSeriesClient<DataSaubDto>, TimeSeriesClient<DataSaubDto>>();
services.AddTransient<ITimestampedSetClient, TimestampedSetClient>();
services.AddTransient<IWitsDataClient, WitsDataClient>();
return services;
}
}

View File

@ -1,16 +0,0 @@
using DD.Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client;
/// <summary>
/// Интерфейс для фабрики, которая создает refit-клиентов
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IRefitClientFactory<T> where T : IRefitClient
{
/// <summary>
/// Создание refit-клиента
/// </summary>
/// <returns></returns>
public T Create();
}

View File

@ -1,52 +0,0 @@
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Client.Helpers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Refit;
using System.Configuration;
using System.Text.Json;
namespace DD.Persistence.Client;
/// <summary>
/// Фабрика, которая создает refit-клиентов
/// </summary>
/// <typeparam name="T"></typeparam>
public class RefitClientFactory<T> : IRefitClientFactory<T> where T : IRefitClient
{
private HttpClient client;
private RefitSettings refitSettings;
/// <inheritdoc/>
public RefitClientFactory(IConfiguration configuration, ILogger<IRefitClientFactory<T>> logger, HttpClient client)
{
//this.client = factory.CreateClient();
this.client = client;
var baseUrl = configuration.GetSection("ClientUrl").Get<string>();
if (String.IsNullOrEmpty(baseUrl))
{
var exception = new SettingsPropertyNotFoundException("В настройках конфигурации не указан адрес Persistence сервиса.");
logger.LogError(exception.Message);
throw exception;
}
client.BaseAddress = new Uri(baseUrl);
JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
refitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
}
/// <summary>
/// создание клиента
/// </summary>
/// <returns></returns>
public T Create()
{
return RestService.For<T>(client, refitSettings);
}
}

View File

@ -1,172 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace DD.Persistence.Database.Postgres.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ChangeLog",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ записи"),
IdDiscriminator = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор таблицы"),
IdAuthor = table.Column<Guid>(type: "uuid", nullable: false, comment: "Автор изменения"),
IdEditor = table.Column<Guid>(type: "uuid", nullable: true, comment: "Редактор"),
Creation = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата создания записи"),
Obsolete = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true, comment: "Дата устаревания (например при удалении)"),
IdNext = table.Column<Guid>(type: "uuid", nullable: true, comment: "Id заменяющей записи"),
DepthStart = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина забоя на дату начала интервала"),
DepthEnd = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина забоя на дату окончания интервала"),
IdSection = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ секции"),
Value = table.Column<string>(type: "jsonb", nullable: false, comment: "Значение")
},
constraints: table =>
{
table.PrimaryKey("PK_ChangeLog", x => x.Id);
});
migrationBuilder.CreateTable(
name: "DataSaub",
columns: table => new
{
date = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
mode = table.Column<int>(type: "integer", nullable: true),
user = table.Column<string>(type: "text", nullable: true),
wellDepth = table.Column<double>(type: "double precision", nullable: true),
bitDepth = table.Column<double>(type: "double precision", nullable: true),
blockPosition = table.Column<double>(type: "double precision", nullable: true),
blockSpeed = table.Column<double>(type: "double precision", nullable: true),
pressure = table.Column<double>(type: "double precision", nullable: true),
axialLoad = table.Column<double>(type: "double precision", nullable: true),
hookWeight = table.Column<double>(type: "double precision", nullable: true),
rotorTorque = table.Column<double>(type: "double precision", nullable: true),
rotorSpeed = table.Column<double>(type: "double precision", nullable: true),
flow = table.Column<double>(type: "double precision", nullable: true),
mseState = table.Column<short>(type: "smallint", nullable: false),
idFeedRegulator = table.Column<int>(type: "integer", nullable: false),
mse = table.Column<double>(type: "double precision", nullable: true),
pump0Flow = table.Column<double>(type: "double precision", nullable: true),
pump1Flow = table.Column<double>(type: "double precision", nullable: true),
pump2Flow = table.Column<double>(type: "double precision", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSaub", x => x.date);
});
migrationBuilder.CreateTable(
name: "DataSourceSystem",
columns: table => new
{
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы - источника данных"),
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы - источника данных"),
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы - источника данных")
},
constraints: table =>
{
table.PrimaryKey("PK_DataSourceSystem", x => x.SystemId);
});
migrationBuilder.CreateTable(
name: "ParameterData",
columns: table => new
{
DiscriminatorId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор системы"),
ParameterId = table.Column<int>(type: "integer", nullable: false, comment: "Id параметра"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Временная отметка"),
Value = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Значение параметра в виде строки")
},
constraints: table =>
{
table.PrimaryKey("PK_ParameterData", x => new { x.DiscriminatorId, x.ParameterId, x.Timestamp });
});
migrationBuilder.CreateTable(
name: "Setpoint",
columns: table => new
{
Key = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ"),
Created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата создания уставки"),
Value = table.Column<object>(type: "jsonb", nullable: false, comment: "Значение уставки"),
IdUser = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id автора последнего изменения")
},
constraints: table =>
{
table.PrimaryKey("PK_Setpoint", x => new { x.Key, x.Created });
});
migrationBuilder.CreateTable(
name: "TimestampedSets",
columns: table => new
{
IdDiscriminator = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор ссылка на тип сохраняемых данных"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Отметка времени, строго в UTC"),
Set = table.Column<string>(type: "jsonb", nullable: false, comment: "Набор сохраняемых данных")
},
constraints: table =>
{
table.PrimaryKey("PK_TimestampedSets", x => new { x.IdDiscriminator, x.Timestamp });
},
comment: "Общая таблица данных временных рядов");
migrationBuilder.CreateTable(
name: "TechMessage",
columns: table => new
{
EventId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id события"),
CategoryId = table.Column<int>(type: "integer", nullable: false, comment: "Id Категории важности"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"),
Text = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы, к которой относится сообщение"),
EventState = table.Column<int>(type: "integer", nullable: false, comment: "Статус события")
},
constraints: table =>
{
table.PrimaryKey("PK_TechMessage", x => x.EventId);
table.ForeignKey(
name: "FK_TechMessage_DataSourceSystem_SystemId",
column: x => x.SystemId,
principalTable: "DataSourceSystem",
principalColumn: "SystemId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_TechMessage_SystemId",
table: "TechMessage",
column: "SystemId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ChangeLog");
migrationBuilder.DropTable(
name: "DataSaub");
migrationBuilder.DropTable(
name: "ParameterData");
migrationBuilder.DropTable(
name: "Setpoint");
migrationBuilder.DropTable(
name: "TechMessage");
migrationBuilder.DropTable(
name: "TimestampedSets");
migrationBuilder.DropTable(
name: "DataSourceSystem");
}
}
}

View File

@ -1,16 +0,0 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DD.Persistence.Database.Entity;
public class DataSourceSystem
{
[Key, Comment("Id системы - источника данных")]
public Guid SystemId { get; set; }
[Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы - источника данных")]
public required string Name { get; set; }
[Comment("Описание системы - источника данных")]
public string? Description { get; set; }
}

View File

@ -1,85 +0,0 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Entity;
using DD.Persistence.Models;
using Xunit;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
namespace DD.Persistence.IntegrationTests.Controllers
{
public class DataSourceSystemControllerTest : BaseIntegrationTest
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly IDataSourceSystemClient dataSourceSystemClient;
private readonly IMemoryCache memoryCache;
public DataSourceSystemControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var refitClientFactory = scope.ServiceProvider
.GetRequiredService<IRefitClientFactory<IRefitDataSourceSystemClient>>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<DataSourceSystemClient>>();
dataSourceSystemClient = scope.ServiceProvider
.GetRequiredService<IDataSourceSystemClient>();
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
}
[Fact]
public async Task Get_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await dataSourceSystemClient.Get(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task Get_AfterSave_returns_success()
{
//arrange
await Add();
//act
var response = await dataSourceSystemClient.Get(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedSystemCount = 1;
var actualSystemCount = response!.Count();
Assert.Equal(expectedSystemCount, actualSystemCount);
}
[Fact]
public async Task Add_returns_success()
{
await Add();
}
private async Task Add()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<DataSourceSystem>();
var dto = new DataSourceSystemDto()
{
SystemId = Guid.NewGuid(),
Name = "Test",
Description = "Test"
};
//act
await dataSourceSystemClient.Add(dto, CancellationToken.None);
}
}
}

View File

@ -1,231 +0,0 @@
using Microsoft.Extensions.DependencyInjection;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Model;
using System.Net;
using Xunit;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Client.Clients;
using Microsoft.Extensions.Logging;
namespace DD.Persistence.IntegrationTests.Controllers
{
public class SetpointControllerTest : BaseIntegrationTest
{
private readonly ISetpointClient setpointClient;
private class TestObject
{
public string? Value1 { get; set; }
public int? Value2 { get; set; }
}
public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var refitClientFactory = scope.ServiceProvider
.GetRequiredService<IRefitClientFactory<IRefitSetpointClient>>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<SetpointClient>>();
setpointClient = scope.ServiceProvider
.GetRequiredService<ISetpointClient>();
}
[Fact]
public async Task GetCurrent_returns_success()
{
//arrange
var setpointKeys = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid()
};
//act
var response = await setpointClient.GetCurrent(setpointKeys, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetCurrent_AfterSave_returns_success()
{
//arrange
var setpointKey = await Add();
//act
var response = await setpointClient.GetCurrent([setpointKey], new CancellationToken());
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(setpointKey, response.FirstOrDefault()?.Key);
}
[Fact]
public async Task GetHistory_returns_success()
{
//arrange
var setpointKeys = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid()
};
var historyMoment = DateTimeOffset.UtcNow;
//act
var response = await setpointClient.GetHistory(setpointKeys, historyMoment, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetHistory_AfterSave_returns_success()
{
//arrange
var setpointKey = await Add();
var historyMoment = DateTimeOffset.UtcNow;
historyMoment = historyMoment.AddDays(1);
//act
var response = await setpointClient.GetHistory([setpointKey], historyMoment, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(setpointKey, response.FirstOrDefault()?.Key);
}
[Fact]
public async Task GetLog_returns_success()
{
//arrange
var setpointKeys = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid()
};
//act
var response = await setpointClient.GetLog(setpointKeys, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetLog_AfterSave_returns_success()
{
//arrange
var setpointKey = await Add();
//act
var response = await setpointClient.GetLog([setpointKey], new CancellationToken());
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(setpointKey, response.FirstOrDefault().Key);
}
[Fact]
public async Task GetDatesRange_returns_success()
{
//arrange
dbContext.CleanupDbSet<Setpoint>();
//act
var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Equal(DateTimeOffset.MinValue, response!.From);
Assert.Equal(DateTimeOffset.MaxValue, response!.To);
}
[Fact]
public async Task GetDatesRange_AfterSave_returns_success()
{
//arrange
dbContext.CleanupDbSet<Setpoint>();
await Add();
var dateBegin = DateTimeOffset.MinValue;
var take = 1;
var part = await setpointClient.GetPart(dateBegin, take, CancellationToken.None);
//act
var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedValue = part!
.FirstOrDefault()!.Created
.ToString("dd.MM.yyyy-HH:mm:ss");
var actualValueFrom = response.From
.ToString("dd.MM.yyyy-HH:mm:ss");
Assert.Equal(expectedValue, actualValueFrom);
var actualValueTo = response.To
.ToString("dd.MM.yyyy-HH:mm:ss");
Assert.Equal(expectedValue, actualValueTo);
}
[Fact]
public async Task GetPart_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 2;
//act
var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetPart_AfterSave_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 1;
await Add();
//act
var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
}
[Fact]
public async Task Save_returns_success()
{
await Add();
}
private async Task<Guid> Add()
{
//arrange
var setpointKey = Guid.NewGuid();
var setpointValue = new TestObject()
{
Value1 = "1",
Value2 = 2
};
//act
await setpointClient.Add(setpointKey, setpointValue, new CancellationToken());
return setpointKey;
}
}
}

View File

@ -1,283 +0,0 @@
using DD.Persistence.Client;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Database.Entity;
using DD.Persistence.Models;
using DD.Persistence.Models.Enumerations;
using DD.Persistence.Models.Requests;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
namespace DD.Persistence.IntegrationTests.Controllers
{
public class TechMessagesControllerTest : BaseIntegrationTest
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly ITechMessagesClient techMessagesClient;
private readonly IMemoryCache memoryCache;
public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var refitClientFactory = scope.ServiceProvider
.GetRequiredService<IRefitClientFactory<IRefitTechMessagesClient>>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<TechMessagesClient>>();
techMessagesClient = scope.ServiceProvider
.GetRequiredService<ITechMessagesClient>();
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
}
[Fact]
public async Task GetPage_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
var requestDto = new PaginationRequest()
{
Skip = 1,
Take = 2,
SortSettings = nameof(TechMessage.CategoryId)
};
//act
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response.Items);
Assert.Equal(requestDto.Skip, response.Skip);
Assert.Equal(requestDto.Take, response.Take);
}
[Fact]
public async Task GetPage_AfterSave_returns_success()
{
//arrange
var dtos = await InsertRange(Guid.NewGuid());
var dtosCount = dtos.Count();
var requestDto = new PaginationRequest()
{
Skip = 0,
Take = 2,
SortSettings = nameof(TechMessage.CategoryId)
};
//act
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Equal(dtosCount, response.Count);
}
[Fact]
public async Task InsertRange_returns_success()
{
await InsertRange(Guid.NewGuid());
}
[Fact]
public async Task InsertRange_returns_BadRequest()
{
//arrange
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
var systemId = Guid.NewGuid();
var dtos = new List<TechMessageDto>()
{
new TechMessageDto()
{
EventId = Guid.NewGuid(),
CategoryId = -1, // < 0
Timestamp = DateTimeOffset.UtcNow,
Text = string.Empty, // length < 0
EventState = EventState.Triggered
}
};
try
{
//act
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
}
catch (Exception ex)
{
//assert
Assert.Equal(exceptionMessage, ex.Message);
}
}
[Fact]
public async Task GetSystems_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetSystems_AfterSave_returns_success()
{
//arrange
await InsertRange(Guid.NewGuid());
//act
var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedSystemCount = 1;
Assert.Equal(expectedSystemCount, response!.Count());
}
[Fact]
public async Task GetStatistics_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
var categoryIds = new[] { 1, 2 };
var systemIds = new[] { Guid.NewGuid() };
//act
var response = await techMessagesClient.GetStatistics(systemIds, categoryIds, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetStatistics_AfterSave_returns_success()
{
//arrange
var categoryIds = new[] { 1 };
var systemId = Guid.NewGuid();
var dtos = await InsertRange(systemId);
var filteredDtos = dtos.Where(e => categoryIds.Contains(e.CategoryId));
//act
var response = await techMessagesClient.GetStatistics([systemId], categoryIds, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
var categories = response
.FirstOrDefault()!.Categories
.Count();
Assert.Equal(filteredDtos.Count(), categories);
}
[Fact]
public async Task GetDatesRange_returns_NoContent()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.Null(response);
}
[Fact]
public async Task GetDatesRange_AfterSave_returns_success()
{
//arrange
await InsertRange(Guid.NewGuid());
//act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.NotNull(response?.From);
Assert.NotNull(response?.To);
}
// [Fact]
// public async Task GetPart_returns_success()
// {
// //arrange
// var dateBegin = DateTimeOffset.UtcNow;
// var take = 2;
// //act
// var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
// //assert
// Assert.NotNull(response);
// Assert.Empty(response);
//}
[Fact]
public async Task GetPart_AfterSave_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 1;
await InsertRange(Guid.NewGuid());
//act
var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
}
private async Task<IEnumerable<TechMessageDto>> InsertRange(Guid systemId)
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
var dtos = new List<TechMessageDto>()
{
new TechMessageDto()
{
EventId = Guid.NewGuid(),
CategoryId = 1,
Timestamp = DateTimeOffset.UtcNow,
Text = nameof(TechMessageDto.Text),
EventState = Models.Enumerations.EventState.Triggered
},
new TechMessageDto()
{
EventId = Guid.NewGuid(),
CategoryId = 2,
Timestamp = DateTimeOffset.UtcNow,
Text = nameof(TechMessageDto.Text),
EventState = Models.Enumerations.EventState.Triggered
}
};
//act
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
//assert
Assert.Equal(dtos.Count, response);
return dtos;
}
}
}

View File

@ -1,43 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!--Генерация NuGet пакета при сборке-->
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<!--Наименование-->
<Title>DD.Persistence.Models</Title>
<!--Версия пакета-->
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<!--Версия сборки-->
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
<!--Id пакета-->
<PackageId>DD.Persistence.Models</PackageId>
<!--Автор-->
<Authors>Digital Drilling</Authors>
<!--Компания-->
<Company>Digital Drilling</Company>
<!--Описание-->
<Description>Пакет для получения dtos для работы с Persistence сервисом</Description>
<!--Url репозитория-->
<RepositoryUrl>https://git.ddrilling.ru/on.nemtina/persistence.git</RepositoryUrl>
<!--тип репозитория-->
<RepositoryType>git</RepositoryType>
<!--Символы отладки-->
<IncludeSymbols>true</IncludeSymbols>
<!--Формат пакета с символами-->
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<!--Путь к пакету-->
<PackageOutputPath>C:\Projects\Nuget\Persistence\Models</PackageOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.3.0" />
</ItemGroup>
</Project>

View File

@ -1,36 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using DD.Persistence.Models;
namespace DD.Persistence.Repository.Repositories;
public class DataSourceSystemCachedRepository : DataSourceSystemRepository
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly IMemoryCache memoryCache;
private const int CacheExpirationInMinutes = 60;
private readonly TimeSpan? AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);
public DataSourceSystemCachedRepository(DbContext db, IMemoryCache memoryCache) : base(db)
{
this.memoryCache = memoryCache;
}
public override async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
await base.Add(dataSourceSystemDto, token);
memoryCache.Remove(SystemCacheKey);
}
public override async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
{
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async (cacheEntry) =>
{
cacheEntry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;
var dtos = await base.Get(token);
return dtos;
});
return systems!;
}
}

View File

@ -1,33 +0,0 @@
using DD.Persistence.Database.Entity;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using Mapster;
using Microsoft.EntityFrameworkCore;
namespace DD.Persistence.Repository.Repositories;
public class DataSourceSystemRepository : IDataSourceSystemRepository
{
protected DbContext db;
public DataSourceSystemRepository(DbContext db)
{
this.db = db;
}
protected virtual IQueryable<DataSourceSystem> GetQueryReadOnly() => db.Set<DataSourceSystem>();
public virtual async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
var entity = dataSourceSystemDto.Adapt<DataSourceSystem>();
await db.Set<DataSourceSystem>().AddAsync(entity, token);
await db.SaveChangesAsync(token);
}
public virtual async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query.ToArrayAsync(token);
var dtos = entities.Select(e => e.Adapt<DataSourceSystemDto>());
return dtos;
}
}

View File

@ -1,22 +0,0 @@
using DD.Persistence.Models;
namespace DD.Persistence.Repositories;
/// <summary>
/// Интерфейс по работе с системами - источниками данных
/// </summary>
public interface IDataSourceSystemRepository
{
/// <summary>
/// Добавить систему
/// </summary>
/// <param name="dataSourceSystemDto"></param>
/// <returns></returns>
public Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
/// <summary>
/// Получить список систем
/// </summary>
/// <returns></returns>
public Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token);
}

View File

@ -1,11 +1,11 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using DD.Persistence.Repositories;
using Persistence.Models;
using Persistence.Models.Requests;
using Persistence.Repositories;
using System.Net;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
[ApiController]
[Authorize]

View File

@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using Persistence.Models;
using Persistence.Repositories;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
/// <summary>
/// Работа с временными данными

View File

@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using Persistence.Models;
using Persistence.Repositories;
using System.Net;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
/// <summary>
/// Работа с уставками

View File

@ -1,11 +1,11 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using DD.Persistence.Repositories;
using Persistence.Models;
using Persistence.Models.Requests;
using Persistence.Repositories;
using System.Net;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
/// <summary>
/// Работа с технологическими сообщениями систем автобурения (АБ)
@ -78,11 +78,11 @@ public class TechMessagesController : ControllerBase
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("range")]
public async Task<ActionResult<DatesRangeDto?>> GetDatesRangeAsync(CancellationToken token)
public async Task<ActionResult<DatesRangeDto>> GetDatesRangeAsync(CancellationToken token)
{
var result = await techMessagesRepository.GetDatesRangeAsync(token);
return result == null ? NoContent() : Ok(result);
return Ok(result);
}
/// <summary>

View File

@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using Persistence.Models;
using Persistence.Repositories;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
[ApiController]
[Authorize]

View File

@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using Persistence.Models;
using Persistence.Repositories;
using System.Net;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
/// <summary>
/// Хранение наборов данных с отметкой времени.

View File

@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DD.Persistence.Models;
using DD.Persistence.Services.Interfaces;
using Persistence.Models;
using Persistence.Services.Interfaces;
using System.Net;
namespace DD.Persistence.API.Controllers;
namespace Persistence.API.Controllers;
/// <summary>
/// Работа с параметрами Wits

View File

@ -3,19 +3,25 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using DD.Persistence.Models;
using DD.Persistence.Models.Configurations;
using DD.Persistence.Services;
using DD.Persistence.Services.Interfaces;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Configurations;
using Persistence.Services;
using Persistence.Services.Interfaces;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using System.Text.Json.Nodes;
using DD.Persistence.Database.Entity;
namespace DD.Persistence.API;
namespace Persistence.API;
public static class DependencyInjection
{
public static void MapsterSetup()
{
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<TechMessageDto, TechMessage>()
.Ignore(dest => dest.System, dest => dest.SystemId);
}
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration)
{
services.AddSwaggerGen(c =>
@ -68,16 +74,15 @@ public static class DependencyInjection
private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var keyCloakHost = configuration["KeyCloakAuthentication:Host"];
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.Audience = configuration["KeyCloakAuthentication:Audience"];
options.MetadataAddress = $"{keyCloakHost}/.well-known/openid-configuration";
options.Audience = configuration["Authentication:Audience"];
options.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = keyCloakHost
ValidIssuer = configuration["Authentication:ValidIssuer"],
};
});
}
@ -138,8 +143,6 @@ public static class DependencyInjection
#region Keycloak
private static void AddKeycloakSecurity(this SwaggerGenOptions options, IConfiguration configuration)
{
var keyCloakHost = configuration["KeyCloakAuthentication:Host"];
options.AddSecurityDefinition("Keycloak", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345token'",
@ -150,7 +153,7 @@ public static class DependencyInjection
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri($"{keyCloakHost}/protocol/openid-connect/auth"),
AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]!),
}
}
});

View File

@ -4,22 +4,21 @@ FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["DD.Persistence.App/DD.Persistence.App.csproj", "DD.Persistence.App/"]
RUN dotnet restore "./DD.Persistence.App/DD.Persistence.App.csproj"
COPY ["Persistence.API/Persistence.API.csproj", "Persistence.API/"]
RUN dotnet restore "./Persistence.API/Persistence.API.csproj"
COPY . .
WORKDIR "/src/DD.Persistence.App"
RUN dotnet build "./DD.Persistence.App.csproj" -c $BUILD_CONFIGURATION -o /app/build
WORKDIR "/src/Persistence.API"
RUN dotnet build "./Persistence.API.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./DD.Persistence.App.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
RUN dotnet publish "./Persistence.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DD.Persistence.App.dll"]
ENTRYPOINT ["dotnet", "Persistence.API.dll"]

View File

@ -1,7 +1,7 @@
using System.ComponentModel;
using System.Security.Claims;
namespace DD.Persistence.API;
namespace Persistence.API;
public static class Extensions
{

View File

@ -1,32 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
<OutputType>Library</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.3.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.2.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence.Database.Postgres\DD.Persistence.Database.Postgres.csproj" />
<ProjectReference Include="..\DD.Persistence.Database\DD.Persistence.Database.csproj" />
<ProjectReference Include="..\DD.Persistence.Repository\DD.Persistence.Repository.csproj" />
<ProjectReference Include="..\DD.Persistence\DD.Persistence.csproj" />
<ProjectReference Include="..\Persistence.Database.Postgres\Persistence.Database.Postgres.csproj" />
<ProjectReference Include="..\Persistence.Repository\Persistence.Repository.csproj" />
<ProjectReference Include="..\Persistence\Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -1,15 +1,10 @@
using DD.Persistence.API;
using System.Globalization;
namespace DD.Persistence.App;
namespace Persistence.API;
public class Program
{
public static void Main(string[] args)
{
CultureInfo uiCulture = CultureInfo.CurrentUICulture;
CultureInfo.CurrentUICulture = new CultureInfo("en-EN");
var host = CreateHostBuilder(args).Build();
Startup.BeforeRunHandler(host);
host.Run();

View File

@ -1,8 +1,8 @@
using DD.Persistence.Database.Model;
using DD.Persistence.Database.Postgres;
using DD.Persistence.Repository;
using Persistence.Database.Model;
using Persistence.Database.Postgres;
using Persistence.Repository;
namespace DD.Persistence.API;
namespace Persistence.API;
public class Startup
{
@ -26,6 +26,8 @@ public class Startup
services.AddJWTAuthentication(Configuration);
services.AddMemoryCache();
services.AddServices();
DependencyInjection.MapsterSetup();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

View File

@ -6,14 +6,16 @@
}
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=persistence;Username=postgres;Password=q;Persist Security Info=True"
"DefaultConnection": "Host=localhost;Database=persistence;Username=postgres;Password=q;Persist Security Info=True"
},
"AllowedHosts": "*",
"NeedUseKeyCloak": false,
"KeyCloakAuthentication": {
"Authentication": {
"MetadataAddress": "http://192.168.0.10:8321/realms/Persistence/.well-known/openid-configuration",
"Audience": "account",
"Host": "http://192.168.0.10:8321/realms/Persistence"
"ValidIssuer": "http://192.168.0.10:8321/realms/Persistence",
"AuthorizationUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/auth"
},
"NeedUseKeyCloak": false,
"AuthUser": {
"username": "myuser",
"password": 12345,

View File

@ -1,8 +1,8 @@
using DD.Persistence.Client.Helpers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using Persistence.Client.Helpers;
using Refit;
namespace DD.Persistence.Client.Clients.Base;
namespace Persistence.Client.Clients.Base;
public abstract class BaseClient
{
private readonly ILogger logger;
@ -12,11 +12,11 @@ public abstract class BaseClient
this.logger = logger;
}
public async Task<T?> ExecuteGetResponse<T>(Func<Task<IApiResponse<T>>> getMethod, CancellationToken token)
public async Task<T> ExecuteGetResponse<T>(Func<Task<IApiResponse<T>>> getMethod, CancellationToken token)
{
var response = await getMethod.Invoke().WaitAsync(token);
if (response.IsSuccessStatusCode)
if (response.IsSuccessful)
{
return response.Content;
}
@ -32,7 +32,7 @@ public abstract class BaseClient
{
var response = await postMethod.Invoke().WaitAsync(token);
if (response.IsSuccessStatusCode)
if (response.IsSuccessful)
{
return;
}
@ -48,7 +48,7 @@ public abstract class BaseClient
{
var response = await postMethod.Invoke().WaitAsync(token);
if (response.IsSuccessStatusCode)
if (response.IsSuccessful)
{
return response.Content;
}

View File

@ -1,23 +1,22 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Models;
using Persistence.Models.Requests;
namespace DD.Persistence.Client.Clients;
namespace Persistence.Client.Clients;
public class ChangeLogClient : BaseClient, IChangeLogClient
{
private readonly IRefitChangeLogClient refitChangeLogClient;
private readonly Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient;
public ChangeLogClient(IRefitClientFactory<IRefitChangeLogClient> refitClientFactory, ILogger<ChangeLogClient> logger) : base(logger)
public ChangeLogClient(Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient, ILogger<ChangeLogClient> logger) : base(logger)
{
this.refitChangeLogClient = refitClientFactory.Create();
}
this.refitChangeLogClient = refitChangeLogClient;
}
public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<int>(
async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token);
return result;
@ -26,7 +25,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<PaginationContainer<DataWithWellDepthAndSectionDto>> GetByDate(Guid idDiscriminator, DateTimeOffset moment,
SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<PaginationContainer<DataWithWellDepthAndSectionDto>>(
async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token);
return result;
@ -34,10 +33,10 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<IEnumerable<ChangeLogDto>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<ChangeLogDto>>(
async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token);
return result!;
return result;
}
public async Task<int> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token)
@ -90,7 +89,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<DatesRangeDto?>(
async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token);
return result;
@ -99,7 +98,5 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public void Dispose()
{
refitChangeLogClient.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@ -1,7 +1,7 @@
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Persistence.Models;
using Persistence.Models.Requests;
namespace DD.Persistence.Client.Clients.Interfaces;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с записями ChangeLog

View File

@ -1,6 +1,6 @@
using DD.Persistence.Models;
using Persistence.Models;
namespace DD.Persistence.Client.Clients.Interfaces;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с уставками

View File

@ -1,7 +1,7 @@
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Persistence.Models;
using Persistence.Models.Requests;
namespace DD.Persistence.Client.Clients.Interfaces;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с технологическими сообщениями
@ -21,7 +21,7 @@ public interface ITechMessagesClient : IDisposable
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token);
Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token);
/// <summary>
/// Получить список технологических сообщений в виде страницы
@ -44,7 +44,7 @@ public interface ITechMessagesClient : IDisposable
/// Получить статистику по системам
/// </summary>
/// <param name="systemIds"></param>
/// <param name="categoryIds"></param>
/// <param name="categoryId"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systemIds, IEnumerable<int> categoryIds, CancellationToken token);
@ -54,5 +54,5 @@ public interface ITechMessagesClient : IDisposable
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token);
Task<IEnumerable<DrillingSystemDto>> GetSystems(CancellationToken token);
}

View File

@ -1,12 +1,12 @@
using DD.Persistence.Models;
using Persistence.Models;
namespace DD.Persistence.Client.Clients.Interfaces;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с временными данными
/// </summary>
/// <typeparam name="TDto"></typeparam>
public interface ITimeSeriesClient<TDto> : IDisposable where TDto : class, ITimeSeriesAbstractDto
public interface ITimeSeriesClient<TDto> : IDisposable where TDto : class, new()
{
/// <summary>
/// Добавление записей

View File

@ -1,6 +1,6 @@
using DD.Persistence.Models;
using Persistence.Models;
namespace DD.Persistence.Client.Clients.Interfaces;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с репозиторием для хранения разных наборов данных рядов.

View File

@ -1,7 +1,7 @@
using DD.Persistence.Models;
using Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с параметрами Wits

View File

@ -1,10 +1,10 @@
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Persistence.Models;
using Persistence.Models.Requests;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitChangeLogClient : IRefitClient, IDisposable
public interface IRefitChangeLogClient : IDisposable
{
private const string BaseRoute = "/api/ChangeLog";

View File

@ -1,9 +1,9 @@
using DD.Persistence.Models;
using Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitSetpointClient : IRefitClient, IDisposable
public interface IRefitSetpointClient : IDisposable
{
private const string BaseRoute = "/api/setpoint";

View File

@ -1,10 +1,11 @@
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit
namespace Persistence.Client.Clients.Interfaces.Refit
{
public interface IRefitTechMessagesClient : IRefitClient, IDisposable
public interface IRefitTechMessagesClient : IDisposable
{
private const string BaseRoute = "/api/techMessages";
@ -15,15 +16,15 @@ namespace DD.Persistence.Client.Clients.Interfaces.Refit
Task<IApiResponse<int>> AddRange(Guid systemId, [Body] IEnumerable<TechMessageDto> dtos, CancellationToken token);
[Get($"{BaseRoute}/systems")]
Task<IApiResponse<IEnumerable<DataSourceSystemDto>>> GetSystems(CancellationToken token);
Task<IApiResponse<IEnumerable<DrillingSystemDto>>> GetSystems(CancellationToken token);
[Get($"{BaseRoute}/range")]
Task<IApiResponse<DatesRangeDto?>> GetDatesRangeAsync(CancellationToken token);
Task<IApiResponse<DatesRangeDto>> GetDatesRangeAsync(CancellationToken token);
[Get($"{BaseRoute}/part")]
Task<IApiResponse<IEnumerable<TechMessageDto>>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
[Get($"{BaseRoute}/statistics")]
Task<IApiResponse<IEnumerable<MessagesStatisticDto>>> GetStatistics([Query(CollectionFormat.Multi)] IEnumerable<Guid> systemIds, [Query(CollectionFormat.Multi)] IEnumerable<int> categoryIds, CancellationToken token);
Task<IApiResponse<IEnumerable<MessagesStatisticDto>>> GetStatistics([Query] IEnumerable<Guid> systemIds, [Query] IEnumerable<int> categoryIds, CancellationToken token);
}
}

View File

@ -1,9 +1,9 @@
using DD.Persistence.Models;
using Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimeSeriesClient<TDto> : IRefitClient, IDisposable
where TDto : class, ITimeSeriesAbstractDto
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimeSeriesClient<TDto> : IDisposable
where TDto : class, new()
{
private const string BaseRoute = "/api/dataSaub";

View File

@ -1,9 +1,9 @@
using DD.Persistence.Models;
using Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimestampedSetClient : IRefitClient, IDisposable
public interface IRefitTimestampedSetClient : IDisposable
{
private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}";

View File

@ -1,8 +1,9 @@
using DD.Persistence.Models;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitWitsDataClient : IRefitClient, IDisposable
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitWitsDataClient : IDisposable
{
private const string BaseRoute = "/api/witsData";

View File

@ -1,58 +1,58 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
namespace DD.Persistence.Client.Clients;
namespace Persistence.Client.Clients;
public class SetpointClient : BaseClient, ISetpointClient
{
private readonly IRefitSetpointClient refitSetpointClient;
public SetpointClient(IRefitClientFactory<IRefitSetpointClient> refitSetpointClientFactory, ILogger<SetpointClient> logger) : base(logger)
public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger<SetpointClient> logger) : base(logger)
{
this.refitSetpointClient = refitSetpointClientFactory.Create();
this.refitSetpointClient = refitSetpointClient;
}
public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<SetpointValueDto>>(
async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token);
return result!;
return result;
}
public async Task<IEnumerable<SetpointValueDto>> GetHistory(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<SetpointValueDto>>(
async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token);
return result!;
return result;
}
public async Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLog(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<Dictionary<Guid, IEnumerable<SetpointLogDto>>>(
async () => await refitSetpointClient.GetLog(setpointKeys, token), token);
return result!;
return result;
}
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<DatesRangeDto>(
async () => await refitSetpointClient.GetDatesRangeAsync(token), token);
return result!;
return result;
}
public async Task<IEnumerable<SetpointLogDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<SetpointLogDto>>(
async () => await refitSetpointClient.GetPart(dateBegin, take, token), token);
return result!;
return result;
}
public async Task Add(Guid setpointKey, object newValue, CancellationToken token)
@ -64,7 +64,5 @@ public class SetpointClient : BaseClient, ISetpointClient
public void Dispose()
{
refitSetpointClient.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@ -1,27 +1,27 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using Persistence.Models.Requests;
namespace DD.Persistence.Client.Clients;
namespace Persistence.Client.Clients;
public class TechMessagesClient : BaseClient, ITechMessagesClient
{
private readonly IRefitTechMessagesClient refitTechMessagesClient;
public TechMessagesClient(IRefitClientFactory<IRefitTechMessagesClient> refitTechMessagesClientFactory, ILogger<TechMessagesClient> logger) : base(logger)
public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger<TechMessagesClient> logger) : base(logger)
{
this.refitTechMessagesClient = refitTechMessagesClientFactory.Create();
this.refitTechMessagesClient = refitTechMessagesClient;
}
public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<PaginationContainer<TechMessageDto>>(
async () => await refitTechMessagesClient.GetPage(request, token), token);
return result!;
return result;
}
public async Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, CancellationToken token)
@ -32,17 +32,17 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
return result;
}
public async Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token)
public async Task<IEnumerable<DrillingSystemDto>> GetSystems(CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<DrillingSystemDto>>(
async () => await refitTechMessagesClient.GetSystems(token), token);
return result!;
return result;
}
public async Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token)
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<DatesRangeDto>(
async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token);
return result;
@ -50,24 +50,22 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
public async Task<IEnumerable<TechMessageDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<TechMessageDto>>(
async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token);
return result!;
return result;
}
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systemIds, IEnumerable<int> categoryIds, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<MessagesStatisticDto>>(
async () => await refitTechMessagesClient.GetStatistics(systemIds, categoryIds, token), token);
return result!;
return result;
}
public void Dispose()
{
refitTechMessagesClient.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@ -1,17 +1,17 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
namespace DD.Persistence.Client.Clients;
public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where TDto : class, ITimeSeriesAbstractDto
namespace Persistence.Client.Clients;
public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where TDto : class, new()
{
private readonly IRefitTimeSeriesClient<TDto> timeSeriesClient;
public TimeSeriesClient(IRefitClientFactory<IRefitTimeSeriesClient<TDto>> refitTechMessagesClientFactory, ILogger<TimeSeriesClient<TDto>> logger) : base(logger)
public TimeSeriesClient(IRefitTimeSeriesClient<TDto> refitTechMessagesClient, ILogger<TimeSeriesClient<TDto>> logger) : base(logger)
{
this.timeSeriesClient = refitTechMessagesClientFactory.Create();
this.timeSeriesClient = refitTechMessagesClient;
}
public async Task<int> AddRange(IEnumerable<TDto> dtos, CancellationToken token)
@ -24,23 +24,23 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
public async Task<IEnumerable<TDto>> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<TDto>>(
async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token);
return result!;
return result;
}
public async Task<IEnumerable<TDto>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<TDto>>(
async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token);
return result!;
return result;
}
public async Task<DatesRangeDto?> GetDatesRange(CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<DatesRangeDto?>(
async () => await timeSeriesClient.GetDatesRange(token), token);
return result;
@ -49,7 +49,5 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
public void Dispose()
{
timeSeriesClient.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@ -1,17 +1,17 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
namespace DD.Persistence.Client.Clients;
namespace Persistence.Client.Clients;
public class TimestampedSetClient : BaseClient, ITimestampedSetClient
{
private readonly IRefitTimestampedSetClient refitTimestampedSetClient;
public TimestampedSetClient(IRefitClientFactory<IRefitTimestampedSetClient> refitTimestampedSetClientFactory, ILogger<TimestampedSetClient> logger) : base(logger)
public TimestampedSetClient(IRefitTimestampedSetClient refitTimestampedSetClient, ILogger<TimestampedSetClient> logger) : base(logger)
{
this.refitTimestampedSetClient = refitTimestampedSetClientFactory.Create();
this.refitTimestampedSetClient = refitTimestampedSetClient;
}
public async Task<int> AddRange(Guid idDiscriminator, IEnumerable<TimestampedSetDto> sets, CancellationToken token)
@ -24,23 +24,23 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
public async Task<IEnumerable<TimestampedSetDto>> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable<string>? columnNames, int skip, int take, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<TimestampedSetDto>>(
async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token);
return result!;
return result;
}
public async Task<IEnumerable<TimestampedSetDto>> GetLast(Guid idDiscriminator, IEnumerable<string>? columnNames, int take, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<TimestampedSetDto>>(
async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token);
return result!;
return result;
}
public async Task<int> Count(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<int>(
async () => await refitTimestampedSetClient.Count(idDiscriminator, token), token);
return result;
@ -48,7 +48,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<DatesRangeDto?>(
async () => await refitTimestampedSetClient.GetDatesRange(idDiscriminator, token), token);
return result;
@ -57,7 +57,5 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
public void Dispose()
{
refitTimestampedSetClient.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@ -1,17 +1,17 @@
using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
namespace DD.Persistence.Client.Clients;
namespace Persistence.Client.Clients;
public class WitsDataClient : BaseClient, IWitsDataClient
{
private readonly IRefitWitsDataClient refitWitsDataClient;
public WitsDataClient(IRefitClientFactory<IRefitWitsDataClient> refitWitsDataClientFactory, ILogger<WitsDataClient> logger) : base(logger)
public WitsDataClient(IRefitWitsDataClient refitWitsDataClient, ILogger<WitsDataClient> logger) : base(logger)
{
this.refitWitsDataClient = refitWitsDataClientFactory.Create();
this.refitWitsDataClient = refitWitsDataClient;
}
public async Task<int> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token)
@ -24,32 +24,30 @@ public class WitsDataClient : BaseClient, IWitsDataClient
public async Task<DatesRangeDto> GetDatesRangeAsync(Guid discriminatorId, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<DatesRangeDto>(
async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token);
return result!;
return result;
}
public async Task<IEnumerable<WitsDataDto>> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token);
return result!;
return result;
}
public async Task<IEnumerable<WitsDataDto>> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token)
{
var result = await ExecuteGetResponse(
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token);
return result!;
return result;
}
public void Dispose()
{
refitWitsDataClient.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Not Acceptable (406)

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Bad gateway (502)

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Forbidden (403)

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Internal Server Error (500)

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Locked (423)

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Service Unavailable Error (503)

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Client.CustomExceptions;
namespace Persistence.Client.CustomExceptions;
/// <summary>
/// Too Many Requests (429)

View File

@ -1,13 +1,13 @@
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using DD.Persistence.Models.Configurations;
using Persistence.Models.Configurations;
using RestSharp;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
namespace DD.Persistence.Client.Helpers;
namespace Persistence.Client.Helpers;
public static class ApiTokenHelper
{
public static void Authorize(this HttpClient httpClient, IConfiguration configuration)

View File

@ -1,8 +1,8 @@
using DD.Persistence.Client.CustomExceptions;
using System.ComponentModel.DataAnnotations;
using Persistence.Client.CustomExceptions;
using Refit;
using System.ComponentModel.DataAnnotations;
namespace DD.Persistence.Client.Helpers;
namespace Persistence.Client.Helpers;
public static class ExceptionsHelper
{
private static readonly Dictionary<System.Net.HttpStatusCode, Exception> ExceptionsDictionary = new Dictionary<System.Net.HttpStatusCode, Exception>()
@ -30,6 +30,6 @@ public static class ExceptionsHelper
var result = exception ?? new Exception("Неопознанная ошибка");
return result;
return result;
}
}

View File

@ -0,0 +1,62 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!--Генерация NuGet пакета при сборке-->
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<!--Наименование-->
<Title>Persistence.Client</Title>
<!--Версия пакета-->
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<!--Версия сборки-->
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
<!--Id пакета-->
<PackageId>Persistence.Client</PackageId>
<!--Автор-->
<Authors>Digital Drilling</Authors>
<!--Компания-->
<Company>Digital Drilling</Company>
<!--Описание-->
<Description>Пакет для получения клиентов для работы с Persistence сервисом</Description>
<!--Url репозитория-->
<RepositoryUrl>https://git.ddrilling.ru/on.nemtina/persistence.git</RepositoryUrl>
<!--тип репозитория-->
<RepositoryType>git</RepositoryType>
<!--Символы отладки-->
<IncludeSymbols>true</IncludeSymbols>
<!--Формат пакета с символами-->
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<!--Путь к пакету-->
<PackageOutputPath>C:\Projects\Nuget</PackageOutputPath>
<!--Readme-->
<PackageReadmeFile>Readme.md</PackageReadmeFile>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<None Include="Readme.md" Pack="true" PackagePath="\"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.2.1" />
<PackageReference Include="Refit" Version="8.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence\Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,132 @@
using Microsoft.Extensions.Configuration;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients;
using Persistence.Client.Helpers;
using Refit;
using Persistence.Factories;
using Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
namespace Persistence.Client
{
/// <summary>
/// Фабрика клиентов для доступа к Persistence - сервису
/// </summary>
public class PersistenceClientFactory
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly IServiceProvider provider;
private HttpClient httpClient;
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IServiceProvider provider, IConfiguration configuration)
{
this.provider = provider;
httpClient = httpClientFactory.CreateClient();
httpClient.Authorize(configuration);
}
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IAuthTokenFactory authTokenFactory, IServiceProvider provider, IConfiguration configuration)
{
this.provider = provider;
httpClient = httpClientFactory.CreateClient();
var token = authTokenFactory.GetToken();
httpClient.Authorize(token);
}
/// <summary>
/// Получить клиент для работы с уставками
/// </summary>
/// <returns></returns>
public ISetpointClient GetSetpointClient()
{
var logger = provider.GetRequiredService<ILogger<SetpointClient>>();
var restClient = RestService.For<IRefitSetpointClient>(httpClient, RefitSettings);
var client = new SetpointClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с технологическими сообщениями
/// </summary>
/// <returns></returns>
public ITechMessagesClient GetTechMessagesClient()
{
var logger = provider.GetRequiredService<ILogger<TechMessagesClient>>();
var restClient = RestService.For<IRefitTechMessagesClient>(httpClient, RefitSettings);
var client = new TechMessagesClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с временными данными
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <returns></returns>
public ITimeSeriesClient<TDto> GetTimeSeriesClient<TDto>()
where TDto : class, new()
{
var logger = provider.GetRequiredService<ILogger<TimeSeriesClient<TDto>>>();
var restClient = RestService.For<IRefitTimeSeriesClient<TDto>>(httpClient, RefitSettings);
var client = new TimeSeriesClient<TDto>(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с данными с отметкой времени
/// </summary>
/// <returns></returns>
public ITimestampedSetClient GetTimestampedSetClient()
{
var logger = provider.GetRequiredService<ILogger<TimestampedSetClient>>();
var restClient = RestService.For<IRefitTimestampedSetClient>(httpClient, RefitSettings);
var client = new TimestampedSetClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с записями ChangeLog
/// </summary>
/// <returns></returns>
public IChangeLogClient GetChangeLogClient()
{
var logger = provider.GetRequiredService<ILogger<ChangeLogClient>>();
var restClient = RestService.For<IRefitChangeLogClient>(httpClient, RefitSettings);
var client = new ChangeLogClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы c параметрами Wits
/// </summary>
/// <returns></returns>
public IWitsDataClient GetWitsDataClient()
{
var logger = provider.GetRequiredService<ILogger<WitsDataClient>>();
var restClient = RestService.For<IRefitWitsDataClient>(httpClient, RefitSettings);
var client = new WitsDataClient(restClient, logger);
return client;
}
}
}

View File

@ -6,7 +6,7 @@ Persistence сервис отвечает за работу с хранимым
## Описание пакета
Данный пакет предоставляет возможность взаимодействия с
Persistence сервисом посредством обращения к конкретному
клиенту, ответственному за работу с одной из областей сервиса.
клиенту, ответсвенному за работу с одной из областей сервиса.
## Список предоставляемых клиентов
- `ISetpointClient` - Клиент для работы с уставками
@ -15,7 +15,6 @@ Persistence сервисом посредством обращения к кон
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
- `IWitsDataClient` - Клиент для работы с параметрами Wits
- `IDataSourceSystemClient` - Клиент для работы с системами
## Использование
Для получения того или иного Persistence - клиента нужно
@ -31,7 +30,7 @@ Persistence сервисом посредством обращения к кон
4. Обратиться к фабрике Persistence - клиентов и получить требуемого клиента.
## xunit тестирование
При написании интеграционных тестов с использованием Persistence - клиентов
При написании интеграционных тестов с ипользованием Persistence - клиентов
Http - клиент не обязан быть авторизован через передачу токена в `PersistenceClientFactory`.
Для осуществления тестовой авторизации достаточно добавить в `appsettings.Tests.json` :
```json

View File

@ -2,7 +2,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DD.Persistence.Database.Model;
namespace Persistence.Database.Model;
public static class DependencyInjection
{

View File

@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Npgsql;
using DD.Persistence.Database.Model;
using Persistence.Database.Model;
namespace DD.Persistence.Database.Postgres;
namespace Persistence.Database.Postgres;
/// <summary>
/// Фабрика контекста для dotnet ef миграций

View File

@ -2,7 +2,7 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Diagnostics;
namespace DD.Persistence.Database.Postgres;
namespace Persistence.Database.Postgres;
public static class EFExtensionsInitialization
{
public static void EnsureCreatedAndMigrated(this DatabaseFacade db)

View File

@ -0,0 +1,35 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
/// <inheritdoc />
public partial class SetpointMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Setpoint",
columns: table => new
{
Key = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ"),
Created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата изменения уставки"),
Value = table.Column<object>(type: "jsonb", nullable: false, comment: "Значение уставки"),
IdUser = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id автора последнего изменения")
},
constraints: table =>
{
table.PrimaryKey("PK_Setpoint", x => new { x.Key, x.Created });
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Setpoint");
}
}
}

View File

@ -0,0 +1,169 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
[DbContext(typeof(PersistenceDbContext))]
[Migration("20241126071115_Add_ChangeLog")]
partial class Add_ChangeLog
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("Id");
b.Property<DateTimeOffset>("Creation")
.HasColumnType("timestamp with time zone")
.HasColumnName("Creation");
b.Property<double>("DepthEnd")
.HasColumnType("double precision")
.HasColumnName("DepthEnd");
b.Property<double>("DepthStart")
.HasColumnType("double precision")
.HasColumnName("DepthStart");
b.Property<Guid>("IdAuthor")
.HasColumnType("uuid")
.HasColumnName("IdAuthor");
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
.HasColumnName("IdDiscriminator");
b.Property<Guid?>("IdEditor")
.HasColumnType("uuid")
.HasColumnName("IdEditor");
b.Property<Guid?>("IdNext")
.HasColumnType("uuid")
.HasColumnName("IdNext");
b.Property<Guid>("IdSection")
.HasColumnType("uuid")
.HasColumnName("IdSection");
b.Property<DateTimeOffset?>("Obsolete")
.HasColumnType("timestamp with time zone")
.HasColumnName("Obsolete");
b.Property<IDictionary<string, object>>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasColumnName("Value");
b.HasKey("Id");
b.ToTable("ChangeLog");
});
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
.HasColumnName("date");
b.Property<double?>("AxialLoad")
.HasColumnType("double precision")
.HasColumnName("axialLoad");
b.Property<double?>("BitDepth")
.HasColumnType("double precision")
.HasColumnName("bitDepth");
b.Property<double?>("BlockPosition")
.HasColumnType("double precision")
.HasColumnName("blockPosition");
b.Property<double?>("BlockSpeed")
.HasColumnType("double precision")
.HasColumnName("blockSpeed");
b.Property<double?>("Flow")
.HasColumnType("double precision")
.HasColumnName("flow");
b.Property<double?>("HookWeight")
.HasColumnType("double precision")
.HasColumnName("hookWeight");
b.Property<int>("IdFeedRegulator")
.HasColumnType("integer")
.HasColumnName("idFeedRegulator");
b.Property<int?>("Mode")
.HasColumnType("integer")
.HasColumnName("mode");
b.Property<double?>("Mse")
.HasColumnType("double precision")
.HasColumnName("mse");
b.Property<short>("MseState")
.HasColumnType("smallint")
.HasColumnName("mseState");
b.Property<double?>("Pressure")
.HasColumnType("double precision")
.HasColumnName("pressure");
b.Property<double?>("Pump0Flow")
.HasColumnType("double precision")
.HasColumnName("pump0Flow");
b.Property<double?>("Pump1Flow")
.HasColumnType("double precision")
.HasColumnName("pump1Flow");
b.Property<double?>("Pump2Flow")
.HasColumnType("double precision")
.HasColumnName("pump2Flow");
b.Property<double?>("RotorSpeed")
.HasColumnType("double precision")
.HasColumnName("rotorSpeed");
b.Property<double?>("RotorTorque")
.HasColumnType("double precision")
.HasColumnName("rotorTorque");
b.Property<string>("User")
.HasColumnType("text")
.HasColumnName("user");
b.Property<double?>("WellDepth")
.HasColumnType("double precision")
.HasColumnName("wellDepth");
b.HasKey("Date");
b.ToTable("DataSaub");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
/// <inheritdoc />
public partial class Add_ChangeLog : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ChangeLog",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
IdDiscriminator = table.Column<Guid>(type: "uuid", nullable: false),
IdAuthor = table.Column<Guid>(type: "uuid", nullable: false),
IdEditor = table.Column<Guid>(type: "uuid", nullable: true),
Creation = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
Obsolete = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
IdNext = table.Column<Guid>(type: "uuid", nullable: true),
DepthStart = table.Column<double>(type: "double precision", nullable: false),
DepthEnd = table.Column<double>(type: "double precision", nullable: false),
IdSection = table.Column<Guid>(type: "uuid", nullable: false),
Value = table.Column<IDictionary<string, object>>(type: "jsonb", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ChangeLog", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ChangeLog");
}
}
}

View File

@ -0,0 +1,162 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
[DbContext(typeof(PersistencePostgresContext))]
[Migration("20241126100631_Init")]
partial class Init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Persistence.Database.Entity.TimestampedSet", b =>
{
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
.HasComment("Дискриминатор ссылка на тип сохраняемых данных");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Отметка времени, строго в UTC");
b.Property<string>("Set")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("Набор сохраняемых данных");
b.HasKey("IdDiscriminator", "Timestamp");
b.ToTable("TimestampedSets", t =>
{
t.HasComment("Общая таблица данных временных рядов");
});
});
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
.HasColumnName("date");
b.Property<double?>("AxialLoad")
.HasColumnType("double precision")
.HasColumnName("axialLoad");
b.Property<double?>("BitDepth")
.HasColumnType("double precision")
.HasColumnName("bitDepth");
b.Property<double?>("BlockPosition")
.HasColumnType("double precision")
.HasColumnName("blockPosition");
b.Property<double?>("BlockSpeed")
.HasColumnType("double precision")
.HasColumnName("blockSpeed");
b.Property<double?>("Flow")
.HasColumnType("double precision")
.HasColumnName("flow");
b.Property<double?>("HookWeight")
.HasColumnType("double precision")
.HasColumnName("hookWeight");
b.Property<int>("IdFeedRegulator")
.HasColumnType("integer")
.HasColumnName("idFeedRegulator");
b.Property<int?>("Mode")
.HasColumnType("integer")
.HasColumnName("mode");
b.Property<double?>("Mse")
.HasColumnType("double precision")
.HasColumnName("mse");
b.Property<short>("MseState")
.HasColumnType("smallint")
.HasColumnName("mseState");
b.Property<double?>("Pressure")
.HasColumnType("double precision")
.HasColumnName("pressure");
b.Property<double?>("Pump0Flow")
.HasColumnType("double precision")
.HasColumnName("pump0Flow");
b.Property<double?>("Pump1Flow")
.HasColumnType("double precision")
.HasColumnName("pump1Flow");
b.Property<double?>("Pump2Flow")
.HasColumnType("double precision")
.HasColumnName("pump2Flow");
b.Property<double?>("RotorSpeed")
.HasColumnType("double precision")
.HasColumnName("rotorSpeed");
b.Property<double?>("RotorTorque")
.HasColumnType("double precision")
.HasColumnName("rotorTorque");
b.Property<string>("User")
.HasColumnType("text")
.HasColumnName("user");
b.Property<double?>("WellDepth")
.HasColumnType("double precision")
.HasColumnName("wellDepth");
b.HasKey("Date");
b.ToTable("DataSaub");
});
modelBuilder.Entity("Persistence.Database.Model.Setpoint", b =>
{
b.Property<Guid>("Key")
.HasColumnType("uuid")
.HasComment("Ключ");
b.Property<DateTimeOffset>("Created")
.HasColumnType("timestamp with time zone")
.HasComment("Дата создания уставки");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasComment("Id автора последнего изменения");
b.Property<object>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("Значение уставки");
b.HasKey("Key", "Created");
b.ToTable("Setpoint");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,87 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("Npgsql:PostgresExtension:adminpack", ",,");
migrationBuilder.CreateTable(
name: "DataSaub",
columns: table => new
{
date = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
mode = table.Column<int>(type: "integer", nullable: true),
user = table.Column<string>(type: "text", nullable: true),
wellDepth = table.Column<double>(type: "double precision", nullable: true),
bitDepth = table.Column<double>(type: "double precision", nullable: true),
blockPosition = table.Column<double>(type: "double precision", nullable: true),
blockSpeed = table.Column<double>(type: "double precision", nullable: true),
pressure = table.Column<double>(type: "double precision", nullable: true),
axialLoad = table.Column<double>(type: "double precision", nullable: true),
hookWeight = table.Column<double>(type: "double precision", nullable: true),
rotorTorque = table.Column<double>(type: "double precision", nullable: true),
rotorSpeed = table.Column<double>(type: "double precision", nullable: true),
flow = table.Column<double>(type: "double precision", nullable: true),
mseState = table.Column<short>(type: "smallint", nullable: false),
idFeedRegulator = table.Column<int>(type: "integer", nullable: false),
mse = table.Column<double>(type: "double precision", nullable: true),
pump0Flow = table.Column<double>(type: "double precision", nullable: true),
pump1Flow = table.Column<double>(type: "double precision", nullable: true),
pump2Flow = table.Column<double>(type: "double precision", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSaub", x => x.date);
});
migrationBuilder.CreateTable(
name: "Setpoint",
columns: table => new
{
Key = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ"),
Created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата создания уставки"),
Value = table.Column<object>(type: "jsonb", nullable: false, comment: "Значение уставки"),
IdUser = table.Column<int>(type: "integer", nullable: false, comment: "Id автора последнего изменения")
},
constraints: table =>
{
table.PrimaryKey("PK_Setpoint", x => new { x.Key, x.Created });
});
migrationBuilder.CreateTable(
name: "TimestampedSets",
columns: table => new
{
IdDiscriminator = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор ссылка на тип сохраняемых данных"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Отметка времени, строго в UTC"),
Set = table.Column<string>(type: "jsonb", nullable: false, comment: "Набор сохраняемых данных")
},
constraints: table =>
{
table.PrimaryKey("PK_TimestampedSets", x => new { x.IdDiscriminator, x.Timestamp });
},
comment: "Общая таблица данных временных рядов");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataSaub");
migrationBuilder.DropTable(
name: "Setpoint");
migrationBuilder.DropTable(
name: "TimestampedSets");
}
}
}

View File

@ -0,0 +1,257 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
[DbContext(typeof(PersistenceDbContext))]
[Migration("20241203120141_ParameterDataMigration")]
partial class ParameterDataMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Persistence.Database.Entity.DrillingSystem", b =>
{
b.Property<Guid>("SystemId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Id системы автобурения");
b.Property<string>("Description")
.HasColumnType("text")
.HasComment("Описание системы автобурения");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Наименование системы автобурения");
b.HasKey("SystemId");
b.ToTable("DrillingSystem");
});
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
{
b.Property<int>("DiscriminatorId")
.HasColumnType("integer")
.HasComment("Дискриминатор системы");
b.Property<int>("ParameterId")
.HasColumnType("integer")
.HasComment("Id параметра");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Временная отметка");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Значение параметра в виде строки");
b.HasKey("DiscriminatorId", "ParameterId", "Timestamp");
b.ToTable("ParameterData");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.Property<Guid>("EventId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Id события");
b.Property<int>("CategoryId")
.HasColumnType("integer")
.HasComment("Id Категории важности");
b.Property<double?>("Depth")
.HasColumnType("double precision")
.HasComment("Глубина забоя");
b.Property<string>("MessageText")
.IsRequired()
.HasColumnType("varchar(512)")
.HasComment("Текст сообщения");
b.Property<Guid>("SystemId")
.HasColumnType("uuid")
.HasComment("Id системы автобурения, к которой относится сообщение");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Дата возникновения");
b.Property<Guid>("UserId")
.HasColumnType("uuid")
.HasComment("Id пользователя за пультом бурильщика");
b.HasKey("EventId");
b.HasIndex("SystemId");
b.ToTable("TechMessage");
});
modelBuilder.Entity("Persistence.Database.Entity.TimestampedSet", b =>
{
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
.HasComment("Дискриминатор ссылка на тип сохраняемых данных");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Отметка времени, строго в UTC");
b.Property<string>("Set")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("Набор сохраняемых данных");
b.HasKey("IdDiscriminator", "Timestamp");
b.ToTable("TimestampedSets", t =>
{
t.HasComment("Общая таблица данных временных рядов");
});
});
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
.HasColumnName("date");
b.Property<double?>("AxialLoad")
.HasColumnType("double precision")
.HasColumnName("axialLoad");
b.Property<double?>("BitDepth")
.HasColumnType("double precision")
.HasColumnName("bitDepth");
b.Property<double?>("BlockPosition")
.HasColumnType("double precision")
.HasColumnName("blockPosition");
b.Property<double?>("BlockSpeed")
.HasColumnType("double precision")
.HasColumnName("blockSpeed");
b.Property<double?>("Flow")
.HasColumnType("double precision")
.HasColumnName("flow");
b.Property<double?>("HookWeight")
.HasColumnType("double precision")
.HasColumnName("hookWeight");
b.Property<int>("IdFeedRegulator")
.HasColumnType("integer")
.HasColumnName("idFeedRegulator");
b.Property<int?>("Mode")
.HasColumnType("integer")
.HasColumnName("mode");
b.Property<double?>("Mse")
.HasColumnType("double precision")
.HasColumnName("mse");
b.Property<short>("MseState")
.HasColumnType("smallint")
.HasColumnName("mseState");
b.Property<double?>("Pressure")
.HasColumnType("double precision")
.HasColumnName("pressure");
b.Property<double?>("Pump0Flow")
.HasColumnType("double precision")
.HasColumnName("pump0Flow");
b.Property<double?>("Pump1Flow")
.HasColumnType("double precision")
.HasColumnName("pump1Flow");
b.Property<double?>("Pump2Flow")
.HasColumnType("double precision")
.HasColumnName("pump2Flow");
b.Property<double?>("RotorSpeed")
.HasColumnType("double precision")
.HasColumnName("rotorSpeed");
b.Property<double?>("RotorTorque")
.HasColumnType("double precision")
.HasColumnName("rotorTorque");
b.Property<string>("User")
.HasColumnType("text")
.HasColumnName("user");
b.Property<double?>("WellDepth")
.HasColumnType("double precision")
.HasColumnName("wellDepth");
b.HasKey("Date");
b.ToTable("DataSaub");
});
modelBuilder.Entity("Persistence.Database.Model.Setpoint", b =>
{
b.Property<Guid>("Key")
.HasColumnType("uuid")
.HasComment("Ключ");
b.Property<DateTimeOffset>("Created")
.HasColumnType("timestamp with time zone")
.HasComment("Дата создания уставки");
b.Property<Guid>("IdUser")
.HasColumnType("uuid")
.HasComment("Id автора последнего изменения");
b.Property<object>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("Значение уставки");
b.HasKey("Key", "Created");
b.ToTable("Setpoint");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.HasOne("Persistence.Database.Entity.DrillingSystem", "System")
.WithMany()
.HasForeignKey("SystemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("System");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
{
/// <inheritdoc />
public partial class ParameterDataMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ParameterData",
columns: table => new
{
DiscriminatorId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор системы"),
ParameterId = table.Column<int>(type: "integer", nullable: false, comment: "Id параметра"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Временная отметка"),
Value = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Значение параметра в виде строки")
},
constraints: table =>
{
table.PrimaryKey("PK_ParameterData", x => new { x.DiscriminatorId, x.ParameterId, x.Timestamp });
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ParameterData");
}
}
}

View File

@ -1,52 +1,54 @@
// <auto-generated />
using System;
using DD.Persistence.Database.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace DD.Persistence.Database.Postgres.Migrations
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
{
[DbContext(typeof(PersistencePostgresContext))]
[Migration("20241220062251_Init")]
partial class Init
[Migration("20241212041758_TechMessageMigration")]
partial class TechMessageMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("DD.Persistence.Database.Entity.DataSourceSystem", b =>
modelBuilder.Entity("Persistence.Database.Entity.DrillingSystem", b =>
{
b.Property<Guid>("SystemId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Id системы - источника данных");
.HasComment("Id системы автобурения");
b.Property<string>("Description")
.HasColumnType("text")
.HasComment("Описание системы - источника данных");
.HasComment("Описание системы автобурения");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Наименование системы - источника данных");
.HasComment("Наименование системы автобурения");
b.HasKey("SystemId");
b.ToTable("DataSourceSystem");
b.ToTable("DrillingSystem");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.ParameterData", b =>
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
{
b.Property<Guid>("DiscriminatorId")
.HasColumnType("uuid")
@ -70,7 +72,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("ParameterData");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.Property<Guid>("EventId")
.ValueGeneratedOnAdd()
@ -105,7 +107,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("TechMessage");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.TimestampedSet", b =>
modelBuilder.Entity("Persistence.Database.Entity.TimestampedSet", b =>
{
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
@ -128,7 +130,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
});
});
modelBuilder.Entity("DD.Persistence.Database.Model.ChangeLog", b =>
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@ -181,7 +183,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("ChangeLog");
});
modelBuilder.Entity("DD.Persistence.Database.Model.DataSaub", b =>
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
@ -264,7 +266,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("DataSaub");
});
modelBuilder.Entity("DD.Persistence.Database.Model.Setpoint", b =>
modelBuilder.Entity("Persistence.Database.Model.Setpoint", b =>
{
b.Property<Guid>("Key")
.HasColumnType("uuid")
@ -288,9 +290,9 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("Setpoint");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.HasOne("DD.Persistence.Database.Entity.DataSourceSystem", "System")
b.HasOne("Persistence.Database.Entity.DrillingSystem", "System")
.WithMany()
.HasForeignKey("SystemId")
.OnDelete(DeleteBehavior.Cascade)

View File

@ -0,0 +1,64 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
{
/// <inheritdoc />
public partial class TechMessageMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DrillingSystem",
columns: table => new
{
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы автобурения"),
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы автобурения"),
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы автобурения")
},
constraints: table =>
{
table.PrimaryKey("PK_DrillingSystem", x => x.SystemId);
});
migrationBuilder.CreateTable(
name: "TechMessage",
columns: table => new
{
EventId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id события"),
CategoryId = table.Column<int>(type: "integer", nullable: false, comment: "Id Категории важности"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"),
Text = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы, к которой относится сообщение"),
EventState = table.Column<int>(type: "integer", nullable: false, comment: "Статус события")
},
constraints: table =>
{
table.PrimaryKey("PK_TechMessage", x => x.EventId);
table.ForeignKey(
name: "FK_TechMessage_DrillingSystem_SystemId",
column: x => x.SystemId,
principalTable: "DrillingSystem",
principalColumn: "SystemId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_TechMessage_SystemId",
table: "TechMessage",
column: "SystemId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TechMessage");
migrationBuilder.DropTable(
name: "DrillingSystem");
}
}
}

View File

@ -1,14 +1,14 @@
// <auto-generated />
using System;
using DD.Persistence.Database.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace DD.Persistence.Database.Postgres.Migrations
namespace Persistence.Database.Postgres.Migrations
{
[DbContext(typeof(PersistencePostgresContext))]
partial class PersistencePostgresContextModelSnapshot : ModelSnapshot
@ -17,33 +17,35 @@ namespace DD.Persistence.Database.Postgres.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("DD.Persistence.Database.Entity.DataSourceSystem", b =>
modelBuilder.Entity("Persistence.Database.Entity.DrillingSystem", b =>
{
b.Property<Guid>("SystemId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Id системы - источника данных");
.HasComment("Id системы автобурения");
b.Property<string>("Description")
.HasColumnType("text")
.HasComment("Описание системы - источника данных");
.HasComment("Описание системы автобурения");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Наименование системы - источника данных");
.HasComment("Наименование системы автобурения");
b.HasKey("SystemId");
b.ToTable("DataSourceSystem");
b.ToTable("DrillingSystem");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.ParameterData", b =>
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
{
b.Property<Guid>("DiscriminatorId")
.HasColumnType("uuid")
@ -67,7 +69,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("ParameterData");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.Property<Guid>("EventId")
.ValueGeneratedOnAdd()
@ -102,7 +104,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("TechMessage");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.TimestampedSet", b =>
modelBuilder.Entity("Persistence.Database.Entity.TimestampedSet", b =>
{
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
@ -125,7 +127,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
});
});
modelBuilder.Entity("DD.Persistence.Database.Model.ChangeLog", b =>
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@ -178,7 +180,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("ChangeLog");
});
modelBuilder.Entity("DD.Persistence.Database.Model.DataSaub", b =>
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
@ -261,7 +263,7 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("DataSaub");
});
modelBuilder.Entity("DD.Persistence.Database.Model.Setpoint", b =>
modelBuilder.Entity("Persistence.Database.Model.Setpoint", b =>
{
b.Property<Guid>("Key")
.HasColumnType("uuid")
@ -285,9 +287,9 @@ namespace DD.Persistence.Database.Postgres.Migrations
b.ToTable("Setpoint");
});
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.HasOne("DD.Persistence.Database.Entity.DataSourceSystem", "System")
b.HasOne("Persistence.Database.Entity.DrillingSystem", "System")
.WithMany()
.HasForeignKey("SystemId")
.OnDelete(DeleteBehavior.Cascade)

View File

@ -1,25 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.0">
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.10" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence.Database\Persistence.Database.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence.Database\DD.Persistence.Database.csproj" />
</ItemGroup>
</Project>

View File

@ -1,6 +1,6 @@
using Microsoft.EntityFrameworkCore;
namespace DD.Persistence.Database.Model;
namespace Persistence.Database.Model;
/// <summary>
/// EF êîíòåêñò äëÿ ÁÄ Postgres
@ -13,6 +13,10 @@ public partial class PersistencePostgresContext : PersistenceDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasPostgresExtension("adminpack")
.HasAnnotation("Relational:Collation", "Russian_Russia.1251");
base.OnModelCreating(modelBuilder);
}
}

View File

@ -1,11 +1,11 @@
## Создать миграцию
```
dotnet ef migrations add <MigrationName> --project DD.Persistence.Database.Postgres
dotnet ef migrations add <MigrationName> --project Persistence.Database.Postgres
```
## Откатить миграцию
```
dotnet ef migrations remove --project DD.Persistence.Database.Postgres
dotnet ef migrations remove --project Persistence.Database.Postgres
```
Удаляется последняя созданная миграция.

View File

@ -2,7 +2,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace DD.Persistence.Database;
namespace Persistence.Database;
public static class EFExtensions
{

View File

@ -1,10 +1,10 @@

using Microsoft.EntityFrameworkCore;
using DD.Persistence.Models;
using Persistence.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DD.Persistence.Database.Model;
namespace Persistence.Database.Model;
/// <summary>
/// Часть записи, описывающая изменение

View File

@ -1,7 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DD.Persistence.Database.Model;
namespace Persistence.Database.Model;
public class DataSaub : ITimestampedData
{
[Key, Column("date")]

View File

@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
public class DrillingSystem
{
[Key, Comment("Id системы автобурения")]
public Guid SystemId { get; set; }
[Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы автобурения")]
public required string Name { get; set; }
[Comment("Описание системы автобурения")]
public string? Description { get; set; }
}

View File

@ -1,5 +1,5 @@

namespace DD.Persistence.Database.Model;
namespace Persistence.Database.Model;
/// <summary>
/// Часть записи, описывающая изменение

View File

@ -1,4 +1,4 @@
namespace DD.Persistence.Database.Model;
namespace Persistence.Database.Model;
public interface ITimestampedData
{
/// <summary>

View File

@ -2,7 +2,7 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DD.Persistence.Database.Entity;
namespace Persistence.Database.Entity;
[PrimaryKey(nameof(DiscriminatorId), nameof(ParameterId), nameof(Timestamp))]
public class ParameterData

View File

@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace DD.Persistence.Database.Model
namespace Persistence.Database.Model
{
[PrimaryKey(nameof(Key), nameof(Created))]
public class Setpoint

Some files were not shown because too many files have changed in this diff Show More