From f13b757a84690770e5ce378a532fcd2867d8ed3e Mon Sep 17 00:00:00 2001 From: KharchenkoVV Date: Wed, 11 Aug 2021 16:54:42 +0500 Subject: [PATCH] CS2-50: All controllers and services are made async --- AsbCloudApp/Services/IAnalyticsService.cs | 16 +++-- AsbCloudApp/Services/IAuthService.cs | 5 +- AsbCloudApp/Services/IClusterService.cs | 16 +++-- AsbCloudApp/Services/IDataService.cs | 12 +++- AsbCloudApp/Services/IEventService.cs | 5 +- AsbCloudApp/Services/IFileService.cs | 6 +- AsbCloudApp/Services/ILastDataService.cs | 11 +++- AsbCloudApp/Services/IMessageService.cs | 13 +++- AsbCloudApp/Services/IReportService.cs | 10 ++- AsbCloudApp/Services/IWellService.cs | 9 +-- AsbCloudDb/Model/AsbCloudDbContext.cs | 23 +++---- AsbCloudDb/Model/IAsbCloudDbContext.cs | 4 +- .../Services/AnalyticsService.cs | 47 +++++++------- .../Services/AuthService.cs | 14 +++-- .../Services/ClusterService.cs | 28 +++++---- .../Services/DataService.cs | 28 +++++---- .../Services/EventService.cs | 7 ++- .../Services/FileService.cs | 10 +-- .../Services/LastDataService.cs | 19 +++--- .../Services/MessageService.cs | 25 +++++--- .../Services/ReportService.cs | 63 ++++++++++--------- .../Services/TelemetryService.cs | 4 +- .../Services/WellService.cs | 16 ++--- .../Controllers/AnalyticsController.cs | 41 +++++++----- AsbCloudWebApi/Controllers/AuthController.cs | 9 ++- .../Controllers/ClusterController.cs | 16 +++-- AsbCloudWebApi/Controllers/DataController.cs | 23 +++++-- .../Controllers/DepositController.cs | 12 ++-- AsbCloudWebApi/Controllers/FileController.cs | 24 ++++--- .../Controllers/LastDataController.cs | 15 +++-- .../Controllers/MessageController.cs | 28 +++++++-- .../Controllers/ReportController.cs | 41 ++++++++---- .../Controllers/TelemetryController.cs | 23 ++++--- AsbCloudWebApi/Controllers/WellController.cs | 15 ++--- .../Controllers/WellSectionController.cs | 23 ++++--- 35 files changed, 417 insertions(+), 244 deletions(-) diff --git a/AsbCloudApp/Services/IAnalyticsService.cs b/AsbCloudApp/Services/IAnalyticsService.cs index d0c83a59..1a5d4f40 100644 --- a/AsbCloudApp/Services/IAnalyticsService.cs +++ b/AsbCloudApp/Services/IAnalyticsService.cs @@ -1,6 +1,7 @@ using AsbCloudApp.Data; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudApp.Services @@ -9,14 +10,19 @@ namespace AsbCloudApp.Services { Task> GetOperationsByWellAsync(int idWell, IEnumerable categoryids = default, DateTime begin = default, - DateTime end = default, int skip = 0, int take = 32); - Task> GetWellDepthToDayAsync(int idWell); + DateTime end = default, int skip = 0, int take = 32, + CancellationToken token = default); + Task> GetWellDepthToDayAsync(int idWell, + CancellationToken token = default); Task> GetWellDepthToIntervalAsync(int idWell, - int intervalHoursTimestamp, int workBeginTimestamp); + int intervalHoursTimestamp, int workBeginTimestamp, + CancellationToken token = default); Task> GetOperationsSummaryAsync(int idWell, - DateTime begin = default, DateTime end = default); + DateTime begin = default, DateTime end = default, + CancellationToken token = default); Task> GetOperationsToIntervalAsync(int idWell, - int intervalHoursTimestamp, int workBeginTimestamp); + int intervalHoursTimestamp, int workBeginTimestamp, + CancellationToken token = default); void SaveAnalytics(DataSaubBaseDto dataSaub); } } diff --git a/AsbCloudApp/Services/IAuthService.cs b/AsbCloudApp/Services/IAuthService.cs index ab7c9e54..621f2c7e 100644 --- a/AsbCloudApp/Services/IAuthService.cs +++ b/AsbCloudApp/Services/IAuthService.cs @@ -1,5 +1,7 @@ using AsbCloudApp.Data; using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Services { @@ -7,7 +9,8 @@ namespace AsbCloudApp.Services { int ChangePassword(int idUser, string newPassword); int ChangePassword(string userLogin, string newPassword); - UserTokenDto Login(string login, string password); + Task LoginAsync(string login, + string password, CancellationToken token = default); string Refresh(ClaimsPrincipal user); int Register(UserDto userDto); diff --git a/AsbCloudApp/Services/IClusterService.cs b/AsbCloudApp/Services/IClusterService.cs index 96a64386..c44fa30c 100644 --- a/AsbCloudApp/Services/IClusterService.cs +++ b/AsbCloudApp/Services/IClusterService.cs @@ -1,15 +1,21 @@ using AsbCloudApp.Data; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudApp.Services { public interface IClusterService { - Task> GetDepositsAsync(int idCompany); - Task> GetClustersAsync(int idCompany, int depositId); - Task> GetClustersAsync(int idCompany); - Task> GetWellsAsync(int idCompany, int clusterId); - Task GetStatAsync(int idCompany, int clusterId); + Task> GetDepositsAsync(int idCompany, + CancellationToken token ); + Task> GetClustersAsync(int idCompany, + int depositId, CancellationToken token ); + Task> GetClustersAsync(int idCompany, + CancellationToken token); + Task> GetWellsAsync(int idCompany, + int clusterId, CancellationToken token); + Task GetStatAsync(int idCompany, + int clusterId, CancellationToken token); } } diff --git a/AsbCloudApp/Services/IDataService.cs b/AsbCloudApp/Services/IDataService.cs index 3f09e7d3..5ceacf65 100644 --- a/AsbCloudApp/Services/IDataService.cs +++ b/AsbCloudApp/Services/IDataService.cs @@ -1,14 +1,20 @@ using AsbCloudApp.Data; using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Services { public interface IDataService { - IEnumerable Get(int idWell, DateTime dateBegin = default, double intervalSec = 600d, int approxPointsCount = 1024); + Task> GetAsync(int idWell, DateTime dateBegin = default, + double intervalSec = 600d, int approxPointsCount = 1024, + CancellationToken token = default); - void UpdateData(string uid, IEnumerable dtos); - DatesRangeDto GetDataDatesRange(int idWell); + Task UpdateDataAsync(string uid, IEnumerable dtos, + CancellationToken token); + Task GetDataDatesRangeAsync(int idWell, + CancellationToken token); } } \ No newline at end of file diff --git a/AsbCloudApp/Services/IEventService.cs b/AsbCloudApp/Services/IEventService.cs index 87f55ad7..26f03d16 100644 --- a/AsbCloudApp/Services/IEventService.cs +++ b/AsbCloudApp/Services/IEventService.cs @@ -1,10 +1,13 @@ using AsbCloudApp.Data; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Services { public interface IEventService { - void Upsert(string uid, IEnumerable dtos); + Task UpsertAsync(string uid, IEnumerable dtos, + CancellationToken token = default); } } diff --git a/AsbCloudApp/Services/IFileService.cs b/AsbCloudApp/Services/IFileService.cs index fabec6eb..63d61fdc 100644 --- a/AsbCloudApp/Services/IFileService.cs +++ b/AsbCloudApp/Services/IFileService.cs @@ -1,6 +1,8 @@ using AsbCloudApp.Data; using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Services { @@ -11,9 +13,9 @@ namespace AsbCloudApp.Services int idCategory, IEnumerable<(string fileName, int idWell, int idCategory, DateTime date, int idUser)> filesInfo); - PaginationContainer GetFilesInfo(int idWell, + Task> GetFilesInfoAsync(int idWell, int idCategory, DateTime begin, DateTime end, - int skip, int take); + int skip, int take, CancellationToken token = default); (int Id, string Name, int IdCategory)? GetFileInfo(int fileId); } diff --git a/AsbCloudApp/Services/ILastDataService.cs b/AsbCloudApp/Services/ILastDataService.cs index 47c785c3..6bec1c83 100644 --- a/AsbCloudApp/Services/ILastDataService.cs +++ b/AsbCloudApp/Services/ILastDataService.cs @@ -1,8 +1,13 @@ -namespace AsbCloudApp.Services +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudApp.Services { public interface ILastDataService { - Tdto Get(int idWell, int idCategory); - void Upsert(int idWell, int idCategory, Tdto value); + Task GetAsync(int idWell, int idCategory, + CancellationToken token); + Task UpsertAsync(int idWell, int idCategory, Tdto value, + CancellationToken token); } } diff --git a/AsbCloudApp/Services/IMessageService.cs b/AsbCloudApp/Services/IMessageService.cs index 3745cd16..097a737c 100644 --- a/AsbCloudApp/Services/IMessageService.cs +++ b/AsbCloudApp/Services/IMessageService.cs @@ -1,13 +1,20 @@ using AsbCloudApp.Data; using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Services { public interface IMessageService { - PaginationContainer GetMessages(int idWell, IEnumerable categoryids = null, DateTime begin = default, DateTime end = default, string searchString = default, int skip = 0, int take = 32); - DatesRangeDto GetMessagesDatesRange(int idWell); - void Insert(string uid, IEnumerable dtos); + Task> GetMessagesAsync(int idWell, + IEnumerable categoryids = null, DateTime begin = default, + DateTime end = default, string searchString = default, + int skip = 0, int take = 32, CancellationToken token = default); + Task GetMessagesDatesRangeAsync(int idWell, + CancellationToken token = default); + Task InsertAsync(string uid, IEnumerable dtos, + CancellationToken token); } } \ No newline at end of file diff --git a/AsbCloudApp/Services/IReportService.cs b/AsbCloudApp/Services/IReportService.cs index 4137f399..939f6083 100644 --- a/AsbCloudApp/Services/IReportService.cs +++ b/AsbCloudApp/Services/IReportService.cs @@ -1,6 +1,8 @@ using AsbCloudApp.Data; using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Services { @@ -13,8 +15,10 @@ namespace AsbCloudApp.Services Action handleReportName); int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int stepSeconds, int format); - IEnumerable GetSuitableReports(int idWell, - DateTime begin, DateTime end, int stepSeconds, int format); - DatesRangeDto GetReportsDatesRange(int idWell); + Task> GetSuitableReportsAsync(int idWell, + DateTime begin, DateTime end, int stepSeconds, int format, + CancellationToken token); + Task GetReportsDatesRangeAsync(int idWell, + CancellationToken token); } } diff --git a/AsbCloudApp/Services/IWellService.cs b/AsbCloudApp/Services/IWellService.cs index 503d0569..2aa8f3be 100644 --- a/AsbCloudApp/Services/IWellService.cs +++ b/AsbCloudApp/Services/IWellService.cs @@ -1,14 +1,15 @@ using AsbCloudApp.Data; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudApp.Services { public interface IWellService { - Task> GetWellsByCompanyAsync(int idCompany); - Task> GetTransmittingWellsAsync(int idCompany); - Task IsCompanyInvolvedInWellAsync(int idCompany, int idWell); - Task> GetOperationsAsync(int idWell); + Task> GetWellsByCompanyAsync(int idCompany, CancellationToken token); + Task> GetTransmittingWellsAsync(int idCompany, CancellationToken token); + Task IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token); + Task> GetOperationsAsync(int idWell, CancellationToken token); } } diff --git a/AsbCloudDb/Model/AsbCloudDbContext.cs b/AsbCloudDb/Model/AsbCloudDbContext.cs index d1632212..37acb870 100644 --- a/AsbCloudDb/Model/AsbCloudDbContext.cs +++ b/AsbCloudDb/Model/AsbCloudDbContext.cs @@ -471,19 +471,20 @@ namespace AsbCloudDb.Model .Include(e => e.Company) .Where(e => e.Login == login); - public (DateTime From, DateTime To) GetDatesRange(int idTelemetry) + public async Task<(DateTime From, DateTime To)> GetDatesRangeAsync(int idTelemetry, + CancellationToken token = default) where TEntity : class, IIdTelemetryDate { var dbSet = Set(); - var datesRange = (from m in dbSet - where m.IdTelemetry == idTelemetry - group m by m.IdTelemetry into g - select new - { - From = g.Min(d => d.Date), - To = g.Max(d => d.Date) - }).AsNoTracking().FirstOrDefault(); + var datesRange = await (from m in dbSet + where m.IdTelemetry == idTelemetry + group m by m.IdTelemetry into g + select new + { + From = g.Min(d => d.Date), + To = g.Max(d => d.Date) + }).AsNoTracking().FirstOrDefaultAsync(token); if (datesRange is null) return (DateTime.MinValue, DateTime.MaxValue); @@ -492,7 +493,7 @@ namespace AsbCloudDb.Model } public async Task> GetDepthToIntervalAsync(int telemetryId, - int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset) + int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset, CancellationToken token) { //TODO: Сменить на LINQ группирование using var command = Database.GetDbConnection().CreateCommand(); @@ -503,7 +504,7 @@ namespace AsbCloudDb.Model GROUP BY floor((extract(epoch from t.date) - {workStartTimestamp} + {timezoneOffset}) / {intervalHoursTimestamp});"; Database.OpenConnection(); - using var reader = await command.ExecuteReaderAsync(); + using var reader = await command.ExecuteReaderAsync(token); IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)> GetResult(DbDataReader rd) { diff --git a/AsbCloudDb/Model/IAsbCloudDbContext.cs b/AsbCloudDb/Model/IAsbCloudDbContext.cs index 7e218e93..0e370c4d 100644 --- a/AsbCloudDb/Model/IAsbCloudDbContext.cs +++ b/AsbCloudDb/Model/IAsbCloudDbContext.cs @@ -40,9 +40,9 @@ namespace AsbCloudDb.Model IQueryable GetWellsForCompany(int idCompany); IQueryable GetUsersByLogin(string login); - (DateTime From, DateTime To) GetDatesRange(int idTelemetry) where T : class, IIdTelemetryDate; + Task<(DateTime From, DateTime To)> GetDatesRangeAsync(int idTelemetry, CancellationToken token) where T : class, IIdTelemetryDate; Task> GetDepthToIntervalAsync(int telemetryId, - int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset); + int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset, CancellationToken token); Task CreatePartitionAsync(string propertyName, int id, CancellationToken token = default) where TEntity : class; } } \ No newline at end of file diff --git a/AsbCloudInfrastructure/Services/AnalyticsService.cs b/AsbCloudInfrastructure/Services/AnalyticsService.cs index af0b3ccf..a2243be3 100644 --- a/AsbCloudInfrastructure/Services/AnalyticsService.cs +++ b/AsbCloudInfrastructure/Services/AnalyticsService.cs @@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services @@ -31,7 +32,7 @@ namespace AsbCloudInfrastructure.Services operationDetectorService = new TelemetryOperationDetectorService(operations); } - public async Task> GetWellDepthToDayAsync(int idWell) + public async Task> GetWellDepthToDayAsync(int idWell, CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); @@ -58,11 +59,11 @@ namespace AsbCloudInfrastructure.Services WellDepth = d.WellDepth ?? 0.0, BitDepth = d.BitDepth ?? 0.0, Date = d.Date - }).AsNoTracking().ToListAsync(); + }).AsNoTracking().ToListAsync(token); } public async Task> GetWellDepthToIntervalAsync(int idWell, - int intervalSeconds, int workBeginSeconds) + int intervalSeconds, int workBeginSeconds, CancellationToken token = default) { intervalSeconds = intervalSeconds == 0 ? 86400 : intervalSeconds; @@ -74,7 +75,7 @@ namespace AsbCloudInfrastructure.Services var timezoneOffset = telemetryService.GetTimezoneOffsetByTelemetryId((int)telemetryId); var drillingPeriodsInfo = await db.GetDepthToIntervalAsync((int)telemetryId, intervalSeconds, - workBeginSeconds, timezoneOffset); + workBeginSeconds, timezoneOffset, token); var wellDepthToIntervalData = drillingPeriodsInfo.Select(d => new WellDepthToIntervalDto { @@ -87,7 +88,7 @@ namespace AsbCloudInfrastructure.Services public async Task> GetOperationsByWellAsync(int idWell, IEnumerable categoryIds = default, DateTime begin = default, - DateTime end = default, int skip = 0, int take = 32) + DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); @@ -121,12 +122,14 @@ namespace AsbCloudInfrastructure.Services operations = operations.Where(m => (m.UnixDate + m.DurationSec) <= unixEnd); } - result.Count = operations.Count(); + result.Count = await operations.CountAsync(token); if (skip > 0) operations = operations.Skip(skip); - var operationsList = await operations.Take(take).AsNoTracking().ToListAsync(); + var operationsList = await operations.Take(take) + .AsNoTracking() + .ToListAsync(token); if (operationsList.Count == 0) return result; @@ -150,7 +153,7 @@ namespace AsbCloudInfrastructure.Services } public async Task> GetOperationsSummaryAsync(int idWell, - DateTime begin = default, DateTime end = default) + DateTime begin = default, DateTime end = default, CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); @@ -160,23 +163,21 @@ namespace AsbCloudInfrastructure.Services var unixBegin = (begin - new DateTime(1970, 1, 1)).TotalSeconds; var unixEnd = (end - new DateTime(1970, 1, 1)).TotalSeconds; - var operations = await (from a in db.TelemetryAnalysis - where a.IdTelemetry == telemetryId && - a.UnixDate > unixBegin && a.UnixDate < unixEnd - join o in db.TelemetryOperations on a.IdOperation equals o.Id - group a by new { a.IdOperation, o.Name } into g - select new TelemetryOperationDurationDto - { - OperationName = g.Key.Name, - Duration = g.Where(g => g.DurationSec > 0) - .Sum(a => a.DurationSec) - }).AsNoTracking().ToListAsync(); - - return operations; + return await (from a in db.TelemetryAnalysis + where a.IdTelemetry == telemetryId && + a.UnixDate > unixBegin && a.UnixDate < unixEnd + join o in db.TelemetryOperations on a.IdOperation equals o.Id + group a by new { a.IdOperation, o.Name } into g + select new TelemetryOperationDurationDto + { + OperationName = g.Key.Name, + Duration = g.Where(g => g.DurationSec > 0) + .Sum(a => a.DurationSec) + }).AsNoTracking().ToListAsync(token); } public async Task> GetOperationsToIntervalAsync(int idWell, - int intervalSeconds, int workBeginSeconds) + int intervalSeconds, int workBeginSeconds, CancellationToken token = default) { intervalSeconds = intervalSeconds == 0 ? 86400 : intervalSeconds; @@ -201,7 +202,7 @@ namespace AsbCloudInfrastructure.Services IntervalStart = g.Min(d => d.UnixDate), OperationName = g.Key.Name, OperationsDuration = g.Sum(an => an.DurationSec) - }).AsNoTracking().ToListAsync(); + }).AsNoTracking().ToListAsync(token); var operationsGroupedByInterval = operations.GroupBy(op => op.IntervalStart) .Select(o => new TelemetryOperationInfoDto diff --git a/AsbCloudInfrastructure/Services/AuthService.cs b/AsbCloudInfrastructure/Services/AuthService.cs index 3ef8028d..1dad61bf 100644 --- a/AsbCloudInfrastructure/Services/AuthService.cs +++ b/AsbCloudInfrastructure/Services/AuthService.cs @@ -10,6 +10,8 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; using Microsoft.EntityFrameworkCore; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -36,9 +38,10 @@ namespace AsbCloudInfrastructure.Services rnd = new Random((int)(DateTime.Now.Ticks % 2147480161)); } - public UserTokenDto Login(string login, string password) + public async Task LoginAsync(string login, string password, + CancellationToken token = default) { - var identity = GetClaimsUser(login, password); + var identity = await GetClaimsUserAsync(login, password, token); if (identity == default) return null; @@ -135,12 +138,13 @@ namespace AsbCloudInfrastructure.Services return new JwtSecurityTokenHandler().WriteToken(jwt); } - private (ClaimsIdentity Identity, User User) GetClaimsUser(string login, string password) + private async Task<(ClaimsIdentity Identity, User User)> GetClaimsUserAsync(string login, + string password, CancellationToken token = default) { - var user = db + var user = await db .GetUsersByLogin(login) .AsNoTracking() - .FirstOrDefault(); + .FirstOrDefaultAsync(token); if (user is null) return default; diff --git a/AsbCloudInfrastructure/Services/ClusterService.cs b/AsbCloudInfrastructure/Services/ClusterService.cs index 0539783e..52e4046e 100644 --- a/AsbCloudInfrastructure/Services/ClusterService.cs +++ b/AsbCloudInfrastructure/Services/ClusterService.cs @@ -4,6 +4,7 @@ using AsbCloudDb.Model; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services @@ -17,7 +18,8 @@ namespace AsbCloudInfrastructure.Services this.db = db; } - public async Task> GetDepositsAsync(int idCompany) + public async Task> GetDepositsAsync(int idCompany, + CancellationToken token = default) { var wellEntities = await (from well in db.Wells .Include(w => w.RelationCompaniesWells) @@ -25,7 +27,7 @@ namespace AsbCloudInfrastructure.Services .Include(w => w.Cluster) .ThenInclude(c => c.Deposit) where well.RelationCompaniesWells.Any(r => r.IdCompany == idCompany) - select well).AsNoTracking().ToListAsync(); + select well).AsNoTracking().ToListAsync(token); var gDepositEntities = wellEntities .GroupBy(w => w.Cluster) @@ -61,13 +63,14 @@ namespace AsbCloudInfrastructure.Services return dtos; } - public async Task> GetClustersAsync(int idCompany) + public async Task> GetClustersAsync(int idCompany, + CancellationToken token = default) { var entities = await db.GetWellsForCompany(idCompany) .Select(e => e.Cluster) .Distinct() .AsNoTracking() - .ToListAsync(); + .ToListAsync(token); var dtos = entities.Select(e => new ClusterDto { @@ -80,14 +83,15 @@ namespace AsbCloudInfrastructure.Services return dtos; } - public async Task> GetClustersAsync(int idCompany, int depositId) + public async Task> GetClustersAsync(int idCompany, + int depositId, CancellationToken token = default) { var entities = await db.GetWellsForCompany(idCompany) .Select(e => e.Cluster) .Where(e => e.IdDeposit == depositId) .Distinct() .AsNoTracking() - .ToListAsync(); + .ToListAsync(token); var dtos = entities.Select(e => new ClusterDto { @@ -100,12 +104,13 @@ namespace AsbCloudInfrastructure.Services return dtos; } - public async Task> GetWellsAsync(int idCompany, int idCluster) + public async Task> GetWellsAsync(int idCompany, + int idCluster, CancellationToken token = default) { var entities = await db.GetWellsForCompany(idCompany) .Where(e => e.IdCluster == idCluster) .AsNoTracking() - .ToListAsync(); + .ToListAsync(token); var dtos = entities.Select(e => new WellDto { @@ -120,7 +125,8 @@ namespace AsbCloudInfrastructure.Services return dtos; } - public async Task GetStatAsync(int idCompany, int idCluster) + public async Task GetStatAsync(int idCompany, + int idCluster, CancellationToken token = default) { var wellEntities = from w in db.Wells where w.IdCluster == idCluster && w.RelationCompaniesWells.Any(c => c.IdCompany == idCompany) @@ -168,12 +174,12 @@ namespace AsbCloudInfrastructure.Services CompanyType = c.Company.CompanyType.Caption, }), WellType = e.WellType.Caption, - }).AsNoTracking().ToListAsync(); + }).AsNoTracking().ToListAsync(token); if (!wellStatDtos.Any()) return null; - var clusterById = db.Clusters.AsNoTracking().FirstOrDefault(c => c.Id == idCluster); + var clusterById = await db.Clusters.AsNoTracking().FirstOrDefaultAsync(c => c.Id == idCluster, token); return new ClusterStatDto { diff --git a/AsbCloudInfrastructure/Services/DataService.cs b/AsbCloudInfrastructure/Services/DataService.cs index 2a317cda..4437ab53 100644 --- a/AsbCloudInfrastructure/Services/DataService.cs +++ b/AsbCloudInfrastructure/Services/DataService.cs @@ -7,6 +7,8 @@ using Mapster; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -28,7 +30,9 @@ namespace AsbCloudInfrastructure.Services cacheWells = cacheDb.GetCachedTable((AsbCloudDbContext)db); } - public IEnumerable Get(int idWell, DateTime dateBegin = default, double intervalSec = 600d, int approxPointsCount = 1024) + public async Task> GetAsync(int idWell, + DateTime dateBegin = default, double intervalSec = 600d, + int approxPointsCount = 1024, CancellationToken token = default) { var well = cacheWells.FirstOrDefault(w => w.Id == idWell); if (well is null) @@ -48,7 +52,7 @@ namespace AsbCloudInfrastructure.Services && data.Date >= dateBegin && data.Date < datEnd select data; - var fullDataCount = query.Count(); + var fullDataCount = await query.CountAsync(token); if (fullDataCount == 0) return default; @@ -60,14 +64,15 @@ namespace AsbCloudInfrastructure.Services query = query.Where(d => d.Id % m == 0); } - var entities = query.AsNoTracking().ToList(); + var entities = await query.AsNoTracking().ToListAsync(token); var dtos = entities.Adapt(); return dtos; } - public void UpdateData(string uid, IEnumerable dtos) + public async Task UpdateDataAsync(string uid, IEnumerable dtos, + CancellationToken token = default) { if (dtos == default || !dtos.Any()) return; @@ -76,11 +81,11 @@ namespace AsbCloudInfrastructure.Services var dtoMinDate = dtos.Min(d => d.Date); var dtoMaxDate = dtos.Max(d => d.Date); - var oldDataSaubBase = (from d in db.DataSaubBases - where d.IdTelemetry == telemetryId - && d.Date > dtoMinDate - && d.Date < dtoMaxDate - select d).AsNoTracking().ToList(); + var oldDataSaubBase = await (from d in db.DataSaubBases + where d.IdTelemetry == telemetryId + && d.Date > dtoMinDate + && d.Date < dtoMaxDate + select d).AsNoTracking().ToListAsync(token); if (oldDataSaubBase.Any()) db.DataSaubBases.RemoveRange(oldDataSaubBase); @@ -99,13 +104,14 @@ namespace AsbCloudInfrastructure.Services db.SaveChanges(); } - public DatesRangeDto GetDataDatesRange(int idWell) + public async Task GetDataDatesRangeAsync(int idWell, + CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); if (telemetryId is null) return null; - var (From, To) = db.GetDatesRange((int)telemetryId); + var (From, To) = await db.GetDatesRangeAsync((int)telemetryId, token); return new DatesRangeDto { From = From, To = To }; } diff --git a/AsbCloudInfrastructure/Services/EventService.cs b/AsbCloudInfrastructure/Services/EventService.cs index 150a6d60..ec6a7db1 100644 --- a/AsbCloudInfrastructure/Services/EventService.cs +++ b/AsbCloudInfrastructure/Services/EventService.cs @@ -4,6 +4,8 @@ using AsbCloudDb.Model; using AsbCloudInfrastructure.Services.Cache; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -18,7 +20,8 @@ namespace AsbCloudInfrastructure.Services cacheEvents = cacheDb.GetCachedTable((AsbCloudDbContext)db); } - public void Upsert(string uid, IEnumerable dtos) + public async Task UpsertAsync(string uid, IEnumerable dtos, + CancellationToken token = default) { if (!dtos.Any()) return; @@ -32,7 +35,7 @@ namespace AsbCloudInfrastructure.Services IdCategory = dto.IdCategory, MessageTemplate = dto.Message }); - cacheEvents.Upsert(entities); + await cacheEvents.UpsertAsync(entities, token); } } } diff --git a/AsbCloudInfrastructure/Services/FileService.cs b/AsbCloudInfrastructure/Services/FileService.cs index daa2efb9..c3ac5c7b 100644 --- a/AsbCloudInfrastructure/Services/FileService.cs +++ b/AsbCloudInfrastructure/Services/FileService.cs @@ -5,6 +5,8 @@ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -43,9 +45,9 @@ namespace AsbCloudInfrastructure.Services return fileIdsToNames; } - public PaginationContainer GetFilesInfo(int idWell, + public async Task> GetFilesInfoAsync(int idWell, int idCategory, DateTime begin = default, DateTime end = default, - int skip = 0, int take = 32) + int skip = 0, int take = 32, CancellationToken token = default) { var filesInfoQuery = db.Files.Include(f => f.User) .Where(f => f.IdWell == idWell && @@ -62,12 +64,12 @@ namespace AsbCloudInfrastructure.Services if (end != default) filesInfoQuery = filesInfoQuery.Where(m => m.Date <= end).AsNoTracking(); - result.Count = filesInfoQuery.Count(); + result.Count = await filesInfoQuery.CountAsync(token); if (skip > 0) filesInfoQuery = filesInfoQuery.Skip(skip).AsNoTracking(); - var filesInfoList = filesInfoQuery.OrderBy(f => f.Date).Take(take).ToList(); + var filesInfoList = await filesInfoQuery.OrderBy(f => f.Date).Take(take).ToListAsync(token); if (filesInfoList.Count == 0) return result; diff --git a/AsbCloudInfrastructure/Services/LastDataService.cs b/AsbCloudInfrastructure/Services/LastDataService.cs index 66aa3119..8042a32d 100644 --- a/AsbCloudInfrastructure/Services/LastDataService.cs +++ b/AsbCloudInfrastructure/Services/LastDataService.cs @@ -1,8 +1,9 @@ using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; -using System.Linq; using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace AsbCloudInfrastructure.Services @@ -16,10 +17,11 @@ namespace AsbCloudInfrastructure.Services this.db = db; } - public Tdto Get(int idWell, int idCategory) + public async Task GetAsync(int idWell, int idCategory, + CancellationToken token = default) { - var entity = db.LastData.AsNoTracking().FirstOrDefault(e => - e.IdWell == idWell && e.IdCategory == idCategory); + var entity = await db.LastData.AsNoTracking().FirstOrDefaultAsync(e => + e.IdWell == idWell && e.IdCategory == idCategory, token); if (entity is null) return new Tdto(); @@ -28,13 +30,14 @@ namespace AsbCloudInfrastructure.Services return dto; } - public void Upsert(int idWell, int idCategory, Tdto value) + public async Task UpsertAsync(int idWell, int idCategory, + Tdto value, CancellationToken token = default) { var model = value.Adapt(); - var entity = db.LastData.AsNoTracking() - .FirstOrDefault(ld => ld.IdWell == idWell && - ld.IdCategory == idCategory); + var entity = await db.LastData.AsNoTracking() + .FirstOrDefaultAsync(ld => ld.IdWell == idWell && + ld.IdCategory == idCategory, token); if (entity is not null) { diff --git a/AsbCloudInfrastructure/Services/MessageService.cs b/AsbCloudInfrastructure/Services/MessageService.cs index 0a07706d..209be08e 100644 --- a/AsbCloudInfrastructure/Services/MessageService.cs +++ b/AsbCloudInfrastructure/Services/MessageService.cs @@ -7,6 +7,8 @@ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -25,14 +27,15 @@ namespace AsbCloudInfrastructure.Services cacheTUsers = cacheDb.GetCachedTable((AsbCloudDbContext)db); } - public PaginationContainer GetMessages( + public async Task> GetMessagesAsync( int idWell, IEnumerable categoryids = default, DateTime begin = default, DateTime end = default, string searchString = default, int skip = 0, - int take = 32) + int take = 32, + CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); if (telemetryId is null) @@ -43,7 +46,8 @@ namespace AsbCloudInfrastructure.Services if (!events.Any()) return null; - var query = db.TelemetryMessages.Where(m => m.IdTelemetry == telemetryId); + var query = db.TelemetryMessages.Where(m => m.IdTelemetry == telemetryId) + .AsNoTracking(); if ((categoryids?.Any() == true) || !string.IsNullOrEmpty(searchString)) { @@ -79,7 +83,8 @@ namespace AsbCloudInfrastructure.Services if (skip > 0) query = query.Skip(skip); - var messagesList = query.Take(take).AsNoTracking().ToList(); + var messagesList = await query.Take(take).AsNoTracking() + .ToListAsync(token); if (messagesList.Count == 0) return result; @@ -108,21 +113,23 @@ namespace AsbCloudInfrastructure.Services return result; } - public DatesRangeDto GetMessagesDatesRange(int idWell) + public async Task GetMessagesDatesRangeAsync(int idWell, + CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); if (telemetryId is null) return null; - var (From, To) = db.GetDatesRange((int)telemetryId); + var (From, To) = await db.GetDatesRangeAsync((int)telemetryId, token); return new DatesRangeDto { From = From, To = To }; } - public void Insert(string uid, IEnumerable dtos) + public Task InsertAsync(string uid, IEnumerable dtos, + CancellationToken token = default) { if (!dtos.Any()) - return; + return null; var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid); @@ -134,7 +141,7 @@ namespace AsbCloudInfrastructure.Services db.TelemetryMessages.Add(entity); } - db.SaveChanges(); + return db.SaveChangesAsync(token); } } } diff --git a/AsbCloudInfrastructure/Services/ReportService.cs b/AsbCloudInfrastructure/Services/ReportService.cs index 9b546c5d..b1980407 100644 --- a/AsbCloudInfrastructure/Services/ReportService.cs +++ b/AsbCloudInfrastructure/Services/ReportService.cs @@ -9,6 +9,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -90,9 +92,10 @@ namespace AsbCloudInfrastructure.Services return generator.GetPagesCount(); } - public IEnumerable GetSuitableReports(int idWell, DateTime begin, DateTime end, int stepSeconds, int format) + public async Task> GetSuitableReportsAsync(int idWell, + DateTime begin, DateTime end, int stepSeconds, int format, CancellationToken token = default) { - var suitableReportsFromDb = GetSuitableReportsFromDb(idWell, begin, end, stepSeconds, format); + var suitableReportsFromDb = await GetSuitableReportsFromDbAsync(idWell, begin, end, stepSeconds, format); var suitableReportsProperties = suitableReportsFromDb.Select(r => new ReportPropertiesDto { @@ -110,27 +113,28 @@ namespace AsbCloudInfrastructure.Services return suitableReportsProperties; } - public DatesRangeDto GetReportsDatesRange(int idWell) + public async Task GetReportsDatesRangeAsync(int idWell, + CancellationToken token = default) { var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); if (telemetryId is null) return null; - var datesRange = (from d in db.DataSaubBases - where d.IdTelemetry == telemetryId - select d.Date).Union( - from m in db.TelemetryMessages - where m.IdTelemetry == telemetryId - select m.Date).DefaultIfEmpty() - .GroupBy(g => true) - .AsNoTracking() - .Select(g => new - { - From = g.Min(), - To = g.Max() - }).OrderBy(gr => gr.From) - .FirstOrDefault(); + var datesRange = await (from d in db.DataSaubBases + where d.IdTelemetry == telemetryId + select d.Date).Union( + from m in db.TelemetryMessages + where m.IdTelemetry == telemetryId + select m.Date).DefaultIfEmpty() + .GroupBy(g => true) + .AsNoTracking() + .Select(g => new + { + From = g.Min(), + To = g.Max() + }).OrderBy(gr => gr.From) + .FirstOrDefaultAsync(token); return new DatesRangeDto { @@ -139,22 +143,25 @@ namespace AsbCloudInfrastructure.Services }; } - private IEnumerable GetSuitableReportsFromDb(int idWell, DateTime begin, DateTime end, int stepSeconds, int format) + private async Task> GetSuitableReportsFromDbAsync(int idWell, + DateTime begin, DateTime end, int stepSeconds, int format, + CancellationToken token = default) { - var suitableReportsNames = (from r in db.ReportProperties.Include(r => r.File) - where r.IdWell == idWell - && r.Begin >= begin - && r.End <= end - && r.Step <= stepSeconds - && r.Format == format - select r).OrderBy(o => o.File.Date) - .AsNoTracking() - .Take(512).ToList(); + var suitableReportsNames = await(from r in db.ReportProperties.Include(r => r.File) + where r.IdWell == idWell + && r.Begin >= begin + && r.End <= end + && r.Step <= stepSeconds + && r.Format == format + select r).OrderBy(o => o.File.Date) + .AsNoTracking() + .Take(512).ToListAsync(token); return suitableReportsNames; } - private IReportGenerator GetReportGenerator(int idWell, DateTime begin, DateTime end, int stepSeconds, int format, AsbCloudDbContext context) + private IReportGenerator GetReportGenerator(int idWell, DateTime begin, + DateTime end, int stepSeconds, int format, AsbCloudDbContext context) { var dataSource = new ReportDataSourcePgCloud(context, idWell); diff --git a/AsbCloudInfrastructure/Services/TelemetryService.cs b/AsbCloudInfrastructure/Services/TelemetryService.cs index d3d495b2..a8382a90 100644 --- a/AsbCloudInfrastructure/Services/TelemetryService.cs +++ b/AsbCloudInfrastructure/Services/TelemetryService.cs @@ -3,6 +3,8 @@ using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services.Cache; using Mapster; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { @@ -47,7 +49,7 @@ namespace AsbCloudInfrastructure.Services var tele = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid, RefreshMode.IfResultEmpty); if (tele is null) return null; - + return cacheWells.FirstOrDefault(w => w?.IdTelemetry == tele.Id); } diff --git a/AsbCloudInfrastructure/Services/WellService.cs b/AsbCloudInfrastructure/Services/WellService.cs index 1475e3e1..50f05eee 100644 --- a/AsbCloudInfrastructure/Services/WellService.cs +++ b/AsbCloudInfrastructure/Services/WellService.cs @@ -25,7 +25,7 @@ namespace AsbCloudInfrastructure.Services cacheRelationCompaniesWells = cacheDb.GetCachedTable((AsbCloudDbContext)db); } - public async Task> GetTransmittingWellsAsync(int idCompany) + public async Task> GetTransmittingWellsAsync(int idCompany, CancellationToken token) { var wells = new List(); IEnumerable activeTelemetriesUids = telemetryTracker.GetTransmittingTelemetryUids(); @@ -34,26 +34,26 @@ namespace AsbCloudInfrastructure.Services wells = await db.GetWellsForCompany(idCompany) .Where(w => activeTelemetriesUids.Contains(w.Telemetry.RemoteUid)) .AsNoTracking() - .ToListAsync(); + .ToListAsync(token); } return wells.Select(w => From(w)); } - public async Task> GetWellsByCompanyAsync(int idCompany) + public async Task> GetWellsByCompanyAsync(int idCompany, CancellationToken token) { - var wells = await db.GetWellsForCompany(idCompany).ToListAsync(); + var wells = await db.GetWellsForCompany(idCompany).ToListAsync(token); return wells.Select(w => From(w)); } - public async Task IsCompanyInvolvedInWellAsync(int idCompany, int idWell) + public async Task IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token) => await cacheRelationCompaniesWells.ContainsAsync(r => r.IdWell == idWell && - r.IdCompany == idCompany, new CancellationToken()); + r.IdCompany == idCompany, token); - public async Task> GetOperationsAsync(int idWell) + public async Task> GetOperationsAsync(int idWell, CancellationToken token) { var entities = await db.WellOperations.Where(o => o.IdWell == idWell) .AsNoTracking() - .ToListAsync(); + .ToListAsync(token); var dtos = entities.Adapt(); diff --git a/AsbCloudWebApi/Controllers/AnalyticsController.cs b/AsbCloudWebApi/Controllers/AnalyticsController.cs index ccf6d5ed..5006fcc7 100644 --- a/AsbCloudWebApi/Controllers/AnalyticsController.cs +++ b/AsbCloudWebApi/Controllers/AnalyticsController.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -32,19 +33,21 @@ namespace AsbCloudWebApi.Controllers /// окончание /// для пагинации кол-во записей пропустить /// для пагинации кол-во записей + /// Токен отмены задачи /// Список операций на скважине за все время [HttpGet] [Route("{idWell}/operationsByWell")] [ProducesResponseType(typeof(PaginationContainer), (int)System.Net.HttpStatusCode.OK)] public async Task GetOperationsByWellAsync(int idWell, int skip = 0, int take = 32, - [FromQuery] IEnumerable categoryIds = default, DateTime begin = default, DateTime end = default) + [FromQuery] IEnumerable categoryIds = default, DateTime begin = default, DateTime end = default, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - var analytics = await analyticsService.GetOperationsByWellAsync(idWell, categoryIds, begin, end, skip, take); + var analytics = await analyticsService.GetOperationsByWellAsync(idWell, categoryIds, begin, end, skip, take, token); if (analytics is null || analytics.Count == 0) return NoContent(); @@ -56,18 +59,20 @@ namespace AsbCloudWebApi.Controllers /// Возвращает данные по скважине "глубина-день" /// /// id скважины + /// Токен отмены задачи /// Коллекцию данных по скважине "глубина-день" [HttpGet] [Route("{idWell}/wellDepthToDay")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetWellDepthToDayAsync(int idWell) + public async Task GetWellDepthToDayAsync(int idWell, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - var wellDepthToDayData = await analyticsService.GetWellDepthToDayAsync(idWell); + var wellDepthToDayData = await analyticsService.GetWellDepthToDayAsync(idWell, token); if (wellDepthToDayData is null || !wellDepthToDayData.Any()) return NoContent(); @@ -81,20 +86,22 @@ namespace AsbCloudWebApi.Controllers /// id скважины /// количество секунд в необходимом интервале времени /// количество секунд в времени начала смены + /// Токен отмены задачи /// Коллекцию данных по глубине скважины за период [HttpGet] [Route("{idWell}/wellDepthToInterval")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] public async Task GetWellDepthToIntervalAsync(int idWell, - int intervalSeconds, int workBeginSeconds) + int intervalSeconds, int workBeginSeconds, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, + idWell, token)) return Forbid(); var wellDepthToIntervalData = await analyticsService.GetWellDepthToIntervalAsync(idWell, - intervalSeconds, workBeginSeconds); + intervalSeconds, workBeginSeconds, token); if (wellDepthToIntervalData is null || !wellDepthToIntervalData.Any()) return NoContent(); @@ -108,18 +115,20 @@ namespace AsbCloudWebApi.Controllers /// id скважины /// дата начала интервала /// дата окончания интервала + /// Токен отмены задачи /// Коллекцию операций на скважине [HttpGet] [Route("{idWell}/operationsSummary")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetOperationsSummaryAsync(int idWell, DateTime begin = default, DateTime end = default) + public async Task GetOperationsSummaryAsync(int idWell, DateTime begin = default, + DateTime end = default, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - var analytics = await analyticsService .GetOperationsSummaryAsync(idWell, begin, end); + var analytics = await analyticsService .GetOperationsSummaryAsync(idWell, begin, end, token); if (analytics is null || !analytics.Any()) return NoContent(); @@ -133,19 +142,21 @@ namespace AsbCloudWebApi.Controllers /// id скважины /// количество секунд в необходимом интервале времени /// количество секунд в времени начала смены + /// Токен отмены задачи /// Коллекцию операций на скважине [HttpGet] [Route("{idWell}/operationsToInterval")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] public async Task GetOperationsToIntervalAsync(int idWell, - int intervalSeconds, int workBeginSeconds) + int intervalSeconds, int workBeginSeconds, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell, token)) return Forbid(); - var analytics = await analyticsService.GetOperationsToIntervalAsync(idWell, intervalSeconds, workBeginSeconds); + var analytics = await analyticsService.GetOperationsToIntervalAsync(idWell, + intervalSeconds, workBeginSeconds, token); if (analytics is null || !analytics.Any()) return NoContent(); diff --git a/AsbCloudWebApi/Controllers/AuthController.cs b/AsbCloudWebApi/Controllers/AuthController.cs index 1133e625..1192ddba 100644 --- a/AsbCloudWebApi/Controllers/AuthController.cs +++ b/AsbCloudWebApi/Controllers/AuthController.cs @@ -2,6 +2,8 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using System.Threading; +using System.Threading.Tasks; using Swashbuckle.AspNetCore.Annotations; namespace AsbCloudWebApi.Controllers @@ -21,15 +23,16 @@ namespace AsbCloudWebApi.Controllers /// Аутентификация пользователя /// /// + /// Токен отмены задачи /// новый токен /// логин и пароль не подходят [AllowAnonymous] [HttpPost("login")] - [SwaggerOperation(OperationId = "logiin")] + [SwaggerOperation(OperationId = "login")] [ProducesResponseType(typeof(UserTokenDto), (int)System.Net.HttpStatusCode.OK)] - public IActionResult Login([FromBody] AuthDto auth) + public async Task LoginAsync([FromBody] AuthDto auth, CancellationToken token = default) { - var userToken = authService.Login(auth.Login, auth.Password); + var userToken = await authService.LoginAsync(auth.Login, auth.Password, token); if (userToken is null) BadRequest();//"wrong login or password" diff --git a/AsbCloudWebApi/Controllers/ClusterController.cs b/AsbCloudWebApi/Controllers/ClusterController.cs index e43ede33..c8a17740 100644 --- a/AsbCloudWebApi/Controllers/ClusterController.cs +++ b/AsbCloudWebApi/Controllers/ClusterController.cs @@ -3,6 +3,7 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -25,17 +26,18 @@ namespace AsbCloudWebApi.Controllers /// /// Получает список доступных пользователю кустов /// + /// Токен отмены задачи /// [HttpGet()] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetClustersAsync() + public async Task GetClustersAsync(CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - var result = await clusterService.GetClustersAsync((int)idCompany); + var result = await clusterService.GetClustersAsync((int)idCompany, token); return Ok(result); } @@ -43,17 +45,18 @@ namespace AsbCloudWebApi.Controllers /// Получение доступных пользователю скважин /// /// + /// Токен отмены задачи /// [HttpGet("{idCluster}")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetWellsAsync(int idCluster) + public async Task GetWellsAsync(int idCluster, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - var result = await clusterService.GetWellsAsync((int)idCompany, idCluster); + var result = await clusterService.GetWellsAsync((int)idCompany, idCluster, token); return Ok(result); } @@ -61,17 +64,18 @@ namespace AsbCloudWebApi.Controllers /// Получение обопщенной статистики по кусту (лучшая/худшая скважина) /// /// + /// Токен отмены задачи /// [HttpGet("{idCluster}/Stat")] [ProducesResponseType(typeof(ClusterStatDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetStatAsync(int idCluster) + public async Task GetStatAsync(int idCluster, CancellationToken token) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - var result = await clusterService.GetStatAsync((int)idCompany, idCluster); + var result = await clusterService.GetStatAsync((int)idCompany, idCluster, token); return Ok(result); } } diff --git a/AsbCloudWebApi/Controllers/DataController.cs b/AsbCloudWebApi/Controllers/DataController.cs index e21007ff..b335f2de 100644 --- a/AsbCloudWebApi/Controllers/DataController.cs +++ b/AsbCloudWebApi/Controllers/DataController.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -34,15 +35,18 @@ namespace AsbCloudWebApi.Controllers /// дата начала выборки. По умолчанию: текущее время - intervalSec /// интервал времени даты начала выборки, секунды /// желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена. + /// Токен завершения задачи /// [HttpGet] [Route("{idWell}/data")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public IActionResult GetData(int idWell, DateTime begin = default, int intervalSec = 600, int approxPointsCount = 1024) + public async Task GetDataAsync(int idWell, DateTime begin = default, + int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default) { if (begin == default) begin = DateTime.Now.AddSeconds(-intervalSec); - var content = telemetryDataService.Get(idWell, begin, intervalSec, approxPointsCount); + var content = await telemetryDataService.GetAsync(idWell, begin, + intervalSec, approxPointsCount, token); if (content is null || !content.Any()) return NoContent(); @@ -50,22 +54,31 @@ namespace AsbCloudWebApi.Controllers return Ok(content); } + /// + /// Возвращает диапазон дат сохраненных данных. + /// + /// id скважины + /// Токен завершения задачи + /// [HttpGet] [Route("{idWell}/dataDatesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetDataDatesRangeAsync(int idWell) + public async Task GetDataDatesRangeAsync(int idWell, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell); + bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, + idWell, token); if (!isCompanyOwnsWell) return Forbid(); - DatesRangeDto dataDatesRange = telemetryDataService.GetDataDatesRange(idWell); + DatesRangeDto dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell, + token); return Ok(dataDatesRange); } diff --git a/AsbCloudWebApi/Controllers/DepositController.cs b/AsbCloudWebApi/Controllers/DepositController.cs index 1bb43de3..28e8192c 100644 --- a/AsbCloudWebApi/Controllers/DepositController.cs +++ b/AsbCloudWebApi/Controllers/DepositController.cs @@ -3,6 +3,7 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -25,17 +26,18 @@ namespace AsbCloudWebApi.Controllers /// /// Получает список доступных пользователю месторождений /// + /// Токен отмены задачи /// [HttpGet] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetDepositsAsync() + public async Task GetDepositsAsync(CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - var result = await clusterService.GetDepositsAsync((int)idCompany); + var result = await clusterService.GetDepositsAsync((int)idCompany, token); return Ok(result); } @@ -43,17 +45,19 @@ namespace AsbCloudWebApi.Controllers /// Получает список доступных пользователю кустов месторождения /// /// + /// Токен отмены задачи /// [HttpGet("{depositId}")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetClustersAsync(int depositId) + public async Task GetClustersAsync(int depositId, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - var result = await clusterService.GetClustersAsync((int)idCompany, depositId); + var result = await clusterService.GetClustersAsync((int)idCompany, depositId, token); return Ok(result); } diff --git a/AsbCloudWebApi/Controllers/FileController.cs b/AsbCloudWebApi/Controllers/FileController.cs index 383272e5..674055c7 100644 --- a/AsbCloudWebApi/Controllers/FileController.cs +++ b/AsbCloudWebApi/Controllers/FileController.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc; using System; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -31,19 +32,20 @@ namespace AsbCloudWebApi.Controllers /// id категории файла /// id отправившего файл пользователя /// Коллекция файлов + /// Токен отмены задачи /// [HttpPost] [Route("{idWell}/files")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task SaveFilesAsync(int idWell, int idCategory, int idUser, - [FromForm] IFormFileCollection files) + public async Task SaveFilesAsync(int idWell, int idCategory, + int idUser, [FromForm] IFormFileCollection files, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); var fileInfoCollection = files.Select(f => @@ -78,21 +80,23 @@ namespace AsbCloudWebApi.Controllers /// дата окончания /// для пагинации кол-во записей пропустить /// для пагинации кол-во записей взять + /// Токен отмены задачи /// Список информации о файлах в этой категории [HttpGet] [Route("{idWell}")] [ProducesResponseType(typeof(PaginationContainer), (int)System.Net.HttpStatusCode.OK)] public async Task GetFilesInfoAsync([FromRoute] int idWell, int skip = 0, int take = 32, int idCategory = default, - DateTime begin = default, DateTime end = default) + DateTime begin = default, DateTime end = default, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, + idWell, token)) return Forbid(); - var filesInfo = fileService.GetFilesInfo(idWell, idCategory, - begin, end, skip, take); + var filesInfo = await fileService.GetFilesInfoAsync(idWell, idCategory, + begin, end, skip, take, token); if (filesInfo is null || !filesInfo.Items.Any()) return NoContent(); @@ -105,11 +109,13 @@ namespace AsbCloudWebApi.Controllers /// /// id скважины /// id запрашиваемого файла + /// Токен отмены задачи /// Запрашиваемый файл [HttpGet] [Route("{idWell}/{fileId}")] [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] - public async Task GetFileAsync([FromRoute] int idWell, int fileId) + public async Task GetFileAsync([FromRoute] int idWell, + int fileId, CancellationToken token = default) { try { @@ -118,7 +124,7 @@ namespace AsbCloudWebApi.Controllers if (idCompany is null) return Forbid(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); var fileInfo = fileService.GetFileInfo(fileId); diff --git a/AsbCloudWebApi/Controllers/LastDataController.cs b/AsbCloudWebApi/Controllers/LastDataController.cs index 746af90e..f3d17abe 100644 --- a/AsbCloudWebApi/Controllers/LastDataController.cs +++ b/AsbCloudWebApi/Controllers/LastDataController.cs @@ -1,6 +1,7 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -19,26 +20,28 @@ namespace AsbCloudWebApi.Controllers } [HttpGet] - public async Task GetAsync([FromRoute] int idWell, [FromQuery] int idCategory) + public async Task GetAsync([FromRoute] int idWell, + [FromQuery] int idCategory, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - var result = lastDataService.Get(idWell, idCategory); + var result = await lastDataService.GetAsync(idWell, idCategory, token); return Ok(result); } [HttpPost] - public async Task PutAsync([FromRoute] int idWell, [FromQuery] int idCategory, T data) + public async Task PutAsync([FromRoute] int idWell, + [FromQuery] int idCategory, T data, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - lastDataService.Upsert(idWell, idCategory, data); + await lastDataService.UpsertAsync(idWell, idCategory, data, token); return Ok(); } } diff --git a/AsbCloudWebApi/Controllers/MessageController.cs b/AsbCloudWebApi/Controllers/MessageController.cs index 6cffa45e..f479761b 100644 --- a/AsbCloudWebApi/Controllers/MessageController.cs +++ b/AsbCloudWebApi/Controllers/MessageController.cs @@ -3,6 +3,7 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -29,11 +30,17 @@ namespace AsbCloudWebApi.Controllers /// окончание /// для пагинации кол-во записей пропустить /// для пагинации кол-во записей + /// Строка поиска + /// Токен для отмены задачи /// список сообщений по скважине [HttpGet] [Route("{idWell}/message")] [ProducesResponseType(typeof(PaginationContainer), (int)System.Net.HttpStatusCode.OK)] - public IActionResult GetMessage(int idWell, int skip = 0, int take = 32, [FromQuery] IEnumerable categoryids = default, DateTime begin = default, DateTime end = default, string searchString = default) + public async Task GetMessagesAsync(int idWell, int skip = 0, int take = 32, + [FromQuery] IEnumerable categoryids = default, + DateTime begin = default, DateTime end = default, + string searchString = default, + CancellationToken token = default) { if (take > 1024) return BadRequest("limit mast be less then 1024"); @@ -41,7 +48,9 @@ namespace AsbCloudWebApi.Controllers if (begin > DateTime.Now) begin = default; - var result = messageService.GetMessages(idWell, categoryids, begin, end, searchString, skip, take); + var result = await messageService.GetMessagesAsync(idWell, + categoryids, begin, end, searchString, + skip, take, token); if (result is null || result.Count == 0) return NoContent(); @@ -49,22 +58,31 @@ namespace AsbCloudWebApi.Controllers return Ok(result); } + /// + /// Выдает список сообщений по скважине + /// + /// id скважины + /// Токен для отмены задачи + /// список сообщений по скважине [HttpGet] [Route("{idWell}/messagesDatesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetMessagesDateRangeAsync(int idWell) + public async Task GetMessagesDateRangeAsync(int idWell, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell); + bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, + idWell, token); if (!isCompanyOwnsWell) return Forbid(); - DatesRangeDto wellMessagesDatesRange = messageService.GetMessagesDatesRange(idWell); + DatesRangeDto wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell, + token); return Ok(wellMessagesDatesRange); } diff --git a/AsbCloudWebApi/Controllers/ReportController.cs b/AsbCloudWebApi/Controllers/ReportController.cs index 9763e3af..766a6f3a 100644 --- a/AsbCloudWebApi/Controllers/ReportController.cs +++ b/AsbCloudWebApi/Controllers/ReportController.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -60,19 +61,21 @@ namespace AsbCloudWebApi.Controllers /// формат отчета (0-PDF, 1-LAS) /// дата начала интервала /// дата окончания интервала + /// Токен для отмены задачи /// id фоновой задачи формирования отчета [HttpPost] [Route("{idWell}/report")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] public async Task CreateReportAsync(int idWell, int idUser, int stepSeconds, int format, - DateTime begin = default, DateTime end = default) + DateTime begin = default, DateTime end = default, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); var id = reportService.CreateReport(idWell, idUser, @@ -86,11 +89,13 @@ namespace AsbCloudWebApi.Controllers /// /// id скважины /// имя запрашиваемого файла (отчета) + /// Токен для отмены задачи /// файл с отчетом [HttpGet] [Route("{idWell}/{reportName}")] [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] - public async Task GetReportAsync([FromRoute] int idWell, string reportName) + public async Task GetReportAsync([FromRoute] int idWell, + string reportName, CancellationToken token = default) { try { @@ -99,7 +104,7 @@ namespace AsbCloudWebApi.Controllers if (idCompany is null) return Forbid(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); // TODO: словарь content typoв var relativePath = Path.Combine(fileService.RootPath, $"{idWell}", @@ -121,14 +126,17 @@ namespace AsbCloudWebApi.Controllers /// формат отчета (0-PDF, 1-LAS) /// дата начала интервала /// дата окончания интервала + /// Токен для отмены задачи /// Список имен существующих отчетов (отчетов) [HttpGet] [Route("{idWell}/suitableReports")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public IActionResult GetSuitableReportsNames(int idWell, int stepSeconds, int format, - DateTime begin = default, DateTime end = default) + public async Task GetSuitableReportsNamesAsync(int idWell, int stepSeconds, int format, + DateTime begin = default, DateTime end = default, + CancellationToken token = default) { - var suitableReportsNames = reportService.GetSuitableReports(idWell, begin, end, stepSeconds, format); + var suitableReportsNames = await reportService.GetSuitableReportsAsync(idWell, + begin, end, stepSeconds, format, token); if (suitableReportsNames is null || !suitableReportsNames.Any()) return NoContent(); @@ -144,21 +152,25 @@ namespace AsbCloudWebApi.Controllers /// дата окончания интервала /// шаг интервала /// формат отчета (0-PDF, 1-LAS) + /// Токен для отмены задачи /// прогнозируемое кол-во страниц отчета [HttpGet] [Route("{idWell}/reportSize")] [ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)] - public async Task GetReportSizeAsync(int idWell, int stepSeconds, int format, DateTime begin = default, DateTime end = default) + public async Task GetReportSizeAsync(int idWell, + int stepSeconds, int format, DateTime begin = default, + DateTime end = default, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - int reportSize = reportService.GetReportPagesCount(idWell, begin, end, stepSeconds, format); + int reportSize = reportService.GetReportPagesCount(idWell, + begin, end, stepSeconds, format); return Ok(reportSize); } @@ -167,21 +179,24 @@ namespace AsbCloudWebApi.Controllers /// Возвращает даты самого старого и самого свежего отчетов в БД /// /// id скважины + /// Токен для отмены задачи /// Даты самого старого и самого свежего отчетов в БД [HttpGet] [Route("{idWell}/reportsDatesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetReportsDateRangeAsync(int idWell) + public async Task GetReportsDateRangeAsync(int idWell, + CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - DatesRangeDto wellReportsDatesRange = reportService.GetReportsDatesRange(idWell); + DatesRangeDto wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell, + token); return Ok(wellReportsDatesRange); } diff --git a/AsbCloudWebApi/Controllers/TelemetryController.cs b/AsbCloudWebApi/Controllers/TelemetryController.cs index e09121fb..d1889333 100644 --- a/AsbCloudWebApi/Controllers/TelemetryController.cs +++ b/AsbCloudWebApi/Controllers/TelemetryController.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -62,16 +63,18 @@ namespace AsbCloudWebApi.Controllers /// /// Уникальный идентификатор отправителя /// Данные + /// Токен для отмены задачи /// [HttpPost] [Route("{uid}/data")] - public IActionResult PostData(string uid, [FromBody] IEnumerable dtos) + public async Task PostDataAsync(string uid, [FromBody] IEnumerable dtos, + CancellationToken token = default) { var idWell = telemetryService.GetidWellByTelemetryUid(uid); - DataService.UpdateData(uid, dtos); + await DataService.UpdateDataAsync(uid, dtos, token); if (idWell != null && dtos.Any()) - Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveDataSaub), dtos)); + await Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveDataSaub), dtos), token); telemetryTracker.SaveRequestDate(uid); return Ok(); @@ -82,16 +85,18 @@ namespace AsbCloudWebApi.Controllers /// /// Уникальный идентификатор отправителя /// сообщения + /// Токен для отмены задачи /// [HttpPost] [Route("{uid}/message")] - public IActionResult PostMessages(string uid, [FromBody] IEnumerable dtos) + public async Task PostMessagesAsync(string uid, [FromBody] IEnumerable dtos, + CancellationToken token = default) { var idWell = telemetryService.GetidWellByTelemetryUid(uid); - messageService.Insert(uid, dtos); + await messageService.InsertAsync(uid, dtos, token); if (dtos.Any()) - Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveMessages), dtos)); + await Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveMessages), dtos), token); telemetryTracker.SaveRequestDate(uid); return Ok(); @@ -102,12 +107,14 @@ namespace AsbCloudWebApi.Controllers /// /// Уникальный идентификатор отправителя /// справочник событий + /// Токен для отмены задачи /// [HttpPost] [Route("{uid}/event")] - public IActionResult PostEvents(string uid, [FromBody] List events) + public async Task PostEventsAsync(string uid, [FromBody] List events, + CancellationToken token = default) { - eventService.Upsert(uid, events); + await eventService.UpsertAsync(uid, events, token); telemetryTracker.SaveRequestDate(uid); return Ok(); } diff --git a/AsbCloudWebApi/Controllers/WellController.cs b/AsbCloudWebApi/Controllers/WellController.cs index eacbb87f..fdc95633 100644 --- a/AsbCloudWebApi/Controllers/WellController.cs +++ b/AsbCloudWebApi/Controllers/WellController.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers @@ -22,7 +23,7 @@ namespace AsbCloudWebApi.Controllers [HttpGet] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetWellsAsync() + public async Task GetWellsAsync(CancellationToken token = default) { var idCompany = User.GetCompanyId(); @@ -31,7 +32,7 @@ namespace AsbCloudWebApi.Controllers return NoContent(); } - var wells = await wellService.GetWellsByCompanyAsync((int)idCompany); + var wells = await wellService.GetWellsByCompanyAsync((int)idCompany, token); if (wells is null || !wells.Any()) return NoContent(); @@ -41,31 +42,31 @@ namespace AsbCloudWebApi.Controllers [HttpGet("{idWell}/operations")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetOperationsAsync(int idWell) + public async Task GetOperationsAsync(int idWell, CancellationToken token = default) { var idCompany = User.GetCompanyId(); if (idCompany is null) return NoContent(); - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) + if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)) return Forbid(); - var dto = await wellService.GetOperationsAsync(idWell); + var dto = await wellService.GetOperationsAsync(idWell, token); return Ok(dto); } [HttpGet("transmittingWells")] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetTransmittingWellsAsync() + public async Task GetTransmittingWellsAsync(CancellationToken token = default) { var idCompany = User.GetCompanyId(); if (idCompany is null) return NoContent(); - var transmittingWells = await wellService.GetTransmittingWellsAsync((int)idCompany); + var transmittingWells = await wellService.GetTransmittingWellsAsync((int)idCompany, token); if (transmittingWells is null || !transmittingWells.Any()) return NoContent(); diff --git a/AsbCloudWebApi/Controllers/WellSectionController.cs b/AsbCloudWebApi/Controllers/WellSectionController.cs index 5a02467e..bb13d194 100644 --- a/AsbCloudWebApi/Controllers/WellSectionController.cs +++ b/AsbCloudWebApi/Controllers/WellSectionController.cs @@ -23,9 +23,10 @@ namespace AsbCloudWebApi.Controllers } [HttpGet] - public async Task GetAllAsync(int idWell, int skip = 0, int take = 32, CancellationToken token = default) + public async Task GetAllAsync(int idWell, int skip = 0, int take = 32, + CancellationToken token = default) { - if(!await CanUserAccessToWellAsync(idWell)) + if(!await CanUserAccessToWellAsync(idWell, token)) return Forbid(); var result = await sectionsService.GetAllByWellIdAsync(idWell, skip, take, token).ConfigureAwait(false); @@ -34,9 +35,10 @@ namespace AsbCloudWebApi.Controllers [HttpGet] [Route("{idSection}")] - public async Task GetAsync(int idSection, int idWell, CancellationToken token = default) + public async Task GetAsync(int idSection, int idWell, + CancellationToken token = default) { - if (!await CanUserAccessToWellAsync(idWell)) + if (!await CanUserAccessToWellAsync(idWell, token)) return Forbid(); var result = await sectionsService.GetAsync(idSection, token).ConfigureAwait(false); @@ -44,9 +46,10 @@ namespace AsbCloudWebApi.Controllers } [HttpPost] - public async Task InsertAsync(int idWell, [FromBody] IEnumerable values, CancellationToken token = default) + public async Task InsertAsync(int idWell, [FromBody] IEnumerable values, + CancellationToken token = default) { - if (!await CanUserAccessToWellAsync(idWell)) + if (!await CanUserAccessToWellAsync(idWell, token)) return Forbid(); var result = await sectionsService.InsertRangeAsync(values, idWell, token).ConfigureAwait(false); @@ -56,7 +59,7 @@ namespace AsbCloudWebApi.Controllers [HttpPut("{id}")] public async Task PutAsync(int id, int idWell, [FromBody] WellSectionDto value, CancellationToken token = default) { - if (!await CanUserAccessToWellAsync(idWell)) + if (!await CanUserAccessToWellAsync(idWell, token)) return Forbid(); var result = await sectionsService.UpdateAsync(value, id, idWell, token).ConfigureAwait(false); @@ -66,17 +69,17 @@ namespace AsbCloudWebApi.Controllers [HttpDelete("{id}")] public async Task DeleteAsync(int id, int idWell, CancellationToken token = default) { - if (!await CanUserAccessToWellAsync(idWell)) + if (!await CanUserAccessToWellAsync(idWell, token)) return Forbid(); var result = await sectionsService.DeleteAsync(new int[] { id }, token).ConfigureAwait(false); return Ok(result); } - private async Task CanUserAccessToWellAsync(int idWell) + private async Task CanUserAccessToWellAsync(int idWell, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); - return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell); + return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token); } } }