1. Типизация клиентских методов signal-R

2. Документирование  клиентских методов signal-R при помощи SignalRSwaggerGen
This commit is contained in:
Olga Nemt 2023-10-30 12:13:38 +05:00
parent 58c9b55631
commit f043253cf2
20 changed files with 191 additions and 43 deletions

View File

@ -14,6 +14,7 @@
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="6.0.8" />
<PackageReference Include="protobuf-net" Version="3.1.17" />
<PackageReference Include="protobuf-net.AspNetCore" Version="3.1.17" />
<PackageReference Include="SignalRSwaggerGen" Version="4.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.4.0" />
</ItemGroup>

View File

@ -5,6 +5,7 @@ using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -28,16 +29,15 @@ public class DrillTestController : ControllerBase
private readonly IDrillTestRepository drillTestRepository;
private readonly IWellService wellService;
private readonly ITelemetryService telemetryService;
private readonly IHubContext<TelemetryHub> telemetryHubContext;
private readonly IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext;
public string SignalRMethodGetDataName { get; protected set; } = "ReceiveDrilltestData";
public DrillTestController(
IDrillTestReportService drillTestReportService,
IDrillTestRepository drillTestRepository,
IWellService wellService,
ITelemetryService telemetryService,
IHubContext<TelemetryHub> telemetryHubContext)
IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext)
{
this.drillTestReportService = drillTestReportService;
this.drillTestRepository = drillTestRepository;
@ -71,7 +71,7 @@ public class DrillTestController : ControllerBase
_ = Task.Run(async () =>
{
var clients = telemetryHubContext.Clients.Group($"well_{idWell}");
await clients.SendAsync(SignalRMethodGetDataName, dto);
await clients.ReceiveDrilltestData(dto, token);
}, CancellationToken.None);
return Ok();

View File

@ -9,6 +9,7 @@ using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -25,7 +26,7 @@ namespace AsbCloudWebApi.Controllers.ProcessMaps;
public abstract class ProcessMapBaseController<T> : ControllerBase
where T : ProcessMapPlanBaseDto
{
private readonly IHubContext<TelemetryHub> telemetryHubContext;
private readonly IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext;
private readonly ITelemetryService telemetryService;
private readonly IWellService wellService;
private readonly IUserRepository userRepository;
@ -36,7 +37,7 @@ public abstract class ProcessMapBaseController<T> : ControllerBase
IProcessMapPlanRepository<T> repository,
IUserRepository userRepository,
ICrudRepository<WellSectionTypeDto> wellSectionRepository,
IHubContext<TelemetryHub> telemetryHubContext,
IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext,
ITelemetryService telemetryService)
{
this.wellService = wellService;
@ -204,7 +205,7 @@ public abstract class ProcessMapBaseController<T> : ControllerBase
await telemetryHubContext.Clients
.Group($"{SignalRMethod}_{idWell}")
.SendAsync("UpdateProcessMap", dtos, cancellationToken);
.UpdateProcessMap<T>(dtos, cancellationToken);
}
private async Task CheckIsExistsWellSectionTypeAsync(int idWellSectionType, CancellationToken cancellationToken)

View File

@ -10,6 +10,7 @@ using AsbCloudApp.Services;
using AsbCloudApp.Services.ProcessMaps;
using AsbCloudApp.Services.ProcessMaps.WellDrilling;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
@ -34,7 +35,7 @@ public class ProcessMapWellDrillingController : ProcessMapBaseController<Process
IProcessMapPlanImportService processMapPlanImportService,
IProcessMapReportWellDrillingService processMapReportWellDrillingService,
ICrudRepository<WellSectionTypeDto> wellSectionRepository,
IHubContext<TelemetryHub> telemetryHubContext,
IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext,
ITelemetryService telemetryService)
: base(wellService, repository, userRepository, wellSectionRepository, telemetryHubContext, telemetryService)
{

View File

@ -3,6 +3,7 @@ using AsbCloudApp.Data.ProcessMaps;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.Controllers.ProcessMaps;
@ -16,7 +17,7 @@ public class ProcessMapWellReamController : ProcessMapBaseController<ProcessMapP
IProcessMapPlanRepository<ProcessMapPlanWellReamDto> repository,
IUserRepository userRepository,
ICrudRepository<WellSectionTypeDto> wellSectionRepository,
IHubContext<TelemetryHub> telemetryHubContext,
IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext,
ITelemetryService telemetryService)
: base(wellService, repository, userRepository, wellSectionRepository, telemetryHubContext, telemetryService)
{

View File

@ -8,6 +8,7 @@ using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Requests;
using AsbCloudWebApi.SignalR.Clients;
namespace AsbCloudWebApi.Controllers
{
@ -57,9 +58,16 @@ namespace AsbCloudWebApi.Controllers
return Forbid();
void HandleReportProgressAsync(object progress, string id) =>
Task.Run(() =>
Task.Run(async() =>
{
reportsHubContext.Clients.Group($"Report_{id}").SendAsync(
//reportsHubContext.Clients.Group($"Report_{id}")
// .GetReportProgressTest(progress, token);
//.ConfigureAwait(false);
//await reportsHubContext.Clients.Group($"Report_{id}")
// .GetReportProgress(progress, token);
await reportsHubContext.Clients.Group($"Report_{id}").SendAsync(
nameof(IReportHubClient.GetReportProgress),
progress,
token

View File

@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System.Linq;
namespace AsbCloudWebApi.Conventions
{
public class ApiExplorerGroupPerVersionConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
controller.ApiExplorer.GroupName = "v1";
}
}
}

View File

@ -46,6 +46,7 @@ namespace AsbCloudWebApi
});
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ASB cloud web api", Version = "v1" });
c.SwaggerDoc("signalr", new OpenApiInfo { Title = "SignalR client methods", Version = "signalr" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
@ -78,6 +79,13 @@ namespace AsbCloudWebApi
var includeControllerXmlComment = true;
c.IncludeXmlComments(xmlPath, includeControllerXmlComment);
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
c.AddSignalRSwaggerGen((_) => {
_.DisplayInDocument("signalr");
_.UseHubXmlCommentsSummaryAsTagDescription = true;
_.UseHubXmlCommentsSummaryAsTag = true;
_.UseXmlComments(xmlPath);
});
});
}

View File

@ -1,9 +1,10 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.SignalR;
public abstract class BaseHub : Hub
public abstract class BaseHub<T> : Hub<T> where T : class
{
public virtual Task AddToGroup(string groupName) =>
Groups.AddToGroupAsync(Context.ConnectionId, groupName);
@ -12,8 +13,7 @@ public abstract class BaseHub : Hub
Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
}
public abstract class BaseHub<T> : BaseHub
where T : class
public abstract class BaseHub2 : Hub
{
}

View File

@ -0,0 +1,22 @@
using AsbCloudWebApi.SignalR.Messages;
using SignalRSwaggerGen.Attributes;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.SignalR.Clients
{
/// <summary>
/// Hub по работе с уведомлениями
/// </summary>
[SignalRHub]
public interface INotificationHubClient
{
/// <summary>
/// Отправка клиенту сообщения с уведомлением
/// </summary>
/// <param name="message">сообщение с уведомлением</param>
/// <param name="token"></param>
/// <returns></returns>
Task ReceiveNotifications(NotificationMessage message, CancellationToken token = default);
}
}

View File

@ -0,0 +1,21 @@
using SignalRSwaggerGen.Attributes;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.SignalR.Clients
{
/// <summary>
/// Hub по работе с отчетами
/// </summary>
[SignalRHub]
public interface IReportHubClient
{
/// <summary>
/// Отправка клиенту сообщения о статусе формирования отчета
/// </summary>
/// <param name="progress">статус формирования отчета</param>
/// <param name="token"></param>
/// <returns></returns>
Task GetReportProgress(object progress, CancellationToken token);
}
}

View File

@ -0,0 +1,34 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.SAUB;
using SignalRSwaggerGen.Attributes;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.SignalR.Clients
{
/// <summary>
/// Hub по работе с телеметрией
/// </summary>
[SignalRHub]
public interface ITelemetryHubClient
{
/// <summary>
/// Отправка клиенту уведомления о доставке с панели drill test данных
/// </summary>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task ReceiveDrilltestData(DrillTestDto dto, CancellationToken token = default);
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task UpdateProcessMap<T>(IEnumerable dtos, CancellationToken token = default);
}
}

View File

@ -0,0 +1,22 @@
using AsbCloudApp.Data;
using SignalRSwaggerGen.Attributes;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.SignalR.Clients
{
/// <summary>
/// Hub по работе с информацией о скважине
/// </summary>
[SignalRHub]
public interface IWellInfoHubClient
{
/// <summary>
/// Отправка клиенту сообщения об обновлении информации о скважине
/// </summary>
/// <param name="wellInfo">информация о скважине</param>
/// <param name="token"></param>
/// <returns></returns>
Task UpdateWellInfo(object wellInfo, CancellationToken token = default);
}
}

View File

@ -1,7 +0,0 @@
namespace AsbCloudWebApi.SignalR
{
public interface IReportHubClient
{
float GetReportProgress(float progress);
}
}

View File

@ -2,6 +2,7 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Services.Notifications;
using AsbCloudWebApi.SignalR.Clients;
using AsbCloudWebApi.SignalR.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@ -9,7 +10,7 @@ using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.SignalR;
[Authorize]
public class NotificationHub : BaseHub
public class NotificationHub : BaseHub<INotificationHubClient>
{
private readonly ConnectionManagerService connectionManagerService;
private readonly NotificationService notificationService;

View File

@ -1,5 +1,6 @@
using AsbCloudApp.Data;
using AsbCloudInfrastructure.Background;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System.Linq;
@ -10,9 +11,13 @@ namespace AsbCloudWebApi.SignalR
{
// SignalR manual:
// https://docs.microsoft.com/ru-ru/aspnet/core/signalr/introduction?view=aspnetcore-5.0
//[SignalRHub]
/// <summary>
/// ReportsHub
/// </summary>
[Authorize]
public class ReportsHub : BaseHub<IReportHubClient>
public class ReportsHub : BaseHub2
//BaseHub<IReportHubClient> //Hub<IReportHubClient> //BaseHub<>
{
private readonly BackgroundWorker backgroundWorker;
@ -21,9 +26,15 @@ namespace AsbCloudWebApi.SignalR
this.backgroundWorker = backgroundWorker;
}
public override async Task AddToGroup(string groupName)
/// <summary>
/// Добавление в группу, отправка данных о формировании отчета
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
public async Task AddToGroup(string groupName)
{
await base.AddToGroup(groupName);
//await this.AddToGroup(groupName);
//await this.Groups.AddToGroupAsync(Context.ConnectionId, groupName);
var workId = groupName.Replace("Report_", "");
var work = backgroundWorker.WorkStore.RunOnceQueue.FirstOrDefault(work => work.Id == workId);
@ -40,13 +51,19 @@ namespace AsbCloudWebApi.SignalR
progress.Operation = state.State;
progress.Progress = (float)state.Progress;
}
await Clients.Group(groupName).SendAsync(
nameof(IReportHubClient.GetReportProgress),
progress,
CancellationToken.None
);
}
//await Clients.Group(groupName).GetReportProgress(progress, CancellationToken.None);
}
//public async Task GetReportProgressTest(object obj, CancellationToken token)
//{
// await Clients.All.GetReportProgressTest(obj, token);
//}
}
}

View File

@ -4,6 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudWebApi.SignalR.Clients;
using AsbCloudWebApi.SignalR.Messages;
using Microsoft.AspNetCore.SignalR;
@ -12,11 +13,11 @@ namespace AsbCloudWebApi.SignalR.Services;
public class NotificationPublisher
{
private readonly ConnectionManagerService connectionManagerService;
private readonly IHubContext<NotificationHub> notificationHubContext;
private readonly IHubContext<NotificationHub, INotificationHubClient> notificationHubContext;
private readonly INotificationRepository notificationRepository;
public NotificationPublisher(ConnectionManagerService connectionManagerService,
IHubContext<NotificationHub> notificationHubContext,
IHubContext<NotificationHub, INotificationHubClient> notificationHubContext,
INotificationRepository notificationRepository)
{
this.connectionManagerService = connectionManagerService;
@ -70,8 +71,6 @@ public class NotificationPublisher
CancellationToken cancellationToken)
{
await notificationHubContext.Clients.Client(connectionId)
.SendAsync("receiveNotifications",
message,
cancellationToken);
.ReceiveNotifications(message, cancellationToken);
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Authorization;
namespace AsbCloudWebApi.SignalR
{
@ -6,7 +7,7 @@ namespace AsbCloudWebApi.SignalR
// https://docs.microsoft.com/ru-ru/aspnet/core/signalr/introduction?view=aspnetcore-5.0
[Authorize]
public class TelemetryHub : BaseHub
public class TelemetryHub : BaseHub<ITelemetryHubClient>
{
}

View File

@ -4,17 +4,18 @@ using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.SignalR;
public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent>
public class WellInfoHub : BaseHub<IWellInfoHubClient>, IIntegrationEventHandler<UpdateWellInfoEvent>
{
private readonly IHubContext<WellInfoHub> hubContext;
private readonly IHubContext<WellInfoHub, IWellInfoHubClient> hubContext;
private readonly IWellService wellService;
private readonly WellInfoService wellInfoService;
public WellInfoHub(IHubContext<WellInfoHub> hubContext,
public WellInfoHub(IHubContext<WellInfoHub, IWellInfoHubClient> hubContext,
IWellService wellService,
WellInfoService wellInfoService)
{
@ -34,8 +35,6 @@ public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent
public async Task HandleAsync(UpdateWellInfoEvent integrationEvent, CancellationToken cancellationToken)
{
const string method = "update_well_info";
var well = await wellService.GetOrDefaultAsync(integrationEvent.IdWell, cancellationToken);
if(well is null)
@ -44,7 +43,7 @@ public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent
var wellInfo = wellInfoService.FirstOrDefault(w => w.Id == well.Id);
await hubContext.Clients.Group($"well_info_{integrationEvent.IdWell}")
.SendAsync(method, new
.UpdateWellInfo(new
{
Well = well,
WellInfo = wellInfo

View File

@ -10,6 +10,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using AsbCloudWebApi.Conventions;
namespace AsbCloudWebApi
{
@ -108,6 +109,10 @@ namespace AsbCloudWebApi
options.EnableForHttps = true;
options.Providers.Add<GzipCompressionProvider>();
});
services.AddMvc(c =>
c.Conventions.Add(new ApiExplorerGroupPerVersionConvention())
);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
@ -116,6 +121,7 @@ namespace AsbCloudWebApi
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1");
c.SwaggerEndpoint("/swagger/signalr/swagger.json", "signalr");
c.EnablePersistAuthorization();
c.EnableFilter();
c.DisplayOperationId();