remove grpc

This commit is contained in:
Stanley Dimant
2024-04-30 11:34:42 +02:00
committed by Loporrit
parent 72df676c9d
commit 348781e5f5
12 changed files with 60 additions and 133 deletions

View File

@@ -49,10 +49,6 @@
"Endpoints": { "Endpoints": {
"Http": { "Http": {
"Url": "http://+:6000" "Url": "http://+:6000"
},
"Grpc": {
"Protocols": "Http2",
"Url": "http://+:6005"
} }
} }
}, },

View File

@@ -0,0 +1,43 @@
using MareSynchronos.API.Data.Enum;
using MareSynchronos.API.SignalR;
using MareSynchronosServer.Hubs;
using MareSynchronosShared.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace MareSynchronosServer.Controllers;
[Route("/msgc")]
[Authorize(Policy = "Internal")]
public class ClientMessageController : Controller
{
private ILogger<ClientMessageController> _logger;
private IHubContext<MareHub, IMareHub> _hubContext;
public ClientMessageController(ILogger<ClientMessageController> logger, IHubContext<MareHub, IMareHub> hubContext)
{
_logger = logger;
_hubContext = hubContext;
}
[Route("sendMessage")]
[HttpPost]
public async Task<IActionResult> SendMessage(ClientMessage msg)
{
bool hasUid = !string.IsNullOrEmpty(msg.UID);
if (!hasUid)
{
_logger.LogInformation("Sending Message of severity {severity} to all online users: {message}", msg.Severity, msg.Message);
await _hubContext.Clients.All.Client_ReceiveServerMessage(msg.Severity, msg.Message).ConfigureAwait(false);
}
else
{
_logger.LogInformation("Sending Message of severity {severity} to user {uid}: {message}", msg.Severity, msg.UID, msg.Message);
await _hubContext.Clients.User(msg.UID).Client_ReceiveServerMessage(msg.Severity, msg.Message).ConfigureAwait(false);
}
return Empty;
}
}

View File

@@ -21,8 +21,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AspNetCoreRateLimit" Version="5.0.0" /> <PackageReference Include="AspNetCoreRateLimit" Version="5.0.0" />
<PackageReference Include="Grpc.AspNetCore" Version="2.62.0" />
<PackageReference Include="Grpc.Net.Client" Version="2.62.0" />
<PackageReference Include="IDisposableAnalyzers" Version="4.0.7"> <PackageReference Include="IDisposableAnalyzers" Version="4.0.7">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

View File

@@ -1,47 +0,0 @@
using Grpc.Core;
using MareSynchronos.API.Data.Enum;
using MareSynchronos.API.SignalR;
using MareSynchronosServer.Hubs;
using MareSynchronosShared.Protos;
using Microsoft.AspNetCore.SignalR;
using static MareSynchronosShared.Protos.ClientMessageService;
namespace MareSynchronosServer.Services;
public class GrpcClientMessageService : ClientMessageServiceBase
{
private readonly ILogger<GrpcClientMessageService> _logger;
private readonly IHubContext<MareHub, IMareHub> _hubContext;
public GrpcClientMessageService(ILogger<GrpcClientMessageService> logger, IHubContext<MareHub, IMareHub> hubContext)
{
_logger = logger;
_hubContext = hubContext;
}
public override async Task<Empty> SendClientMessage(ClientMessage request, ServerCallContext context)
{
bool hasUid = !string.IsNullOrEmpty(request.Uid);
var severity = request.Type switch
{
MessageType.Info => MessageSeverity.Information,
MessageType.Warning => MessageSeverity.Warning,
MessageType.Error => MessageSeverity.Error,
_ => MessageSeverity.Information,
};
if (!hasUid)
{
_logger.LogInformation("Sending Message of severity {severity} to all online users: {message}", severity, request.Message);
await _hubContext.Clients.All.Client_ReceiveServerMessage(severity, request.Message).ConfigureAwait(false);
}
else
{
_logger.LogInformation("Sending Message of severity {severity} to user {uid}: {message}", severity, request.Uid, request.Message);
await _hubContext.Clients.User(request.Uid).Client_ReceiveServerMessage(severity, request.Message).ConfigureAwait(false);
}
return new Empty();
}
}

View File

@@ -5,8 +5,6 @@ using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using AspNetCoreRateLimit; using AspNetCoreRateLimit;
using MareSynchronosShared.Data; using MareSynchronosShared.Data;
using MareSynchronosShared.Protos;
using Grpc.Net.Client.Configuration;
using MareSynchronosShared.Metrics; using MareSynchronosShared.Metrics;
using MareSynchronosServer.Services; using MareSynchronosServer.Services;
using MareSynchronosShared.Utils; using MareSynchronosShared.Utils;
@@ -73,7 +71,7 @@ public class Startup
a.FeatureProviders.Remove(a.FeatureProviders.OfType<ControllerFeatureProvider>().First()); a.FeatureProviders.Remove(a.FeatureProviders.OfType<ControllerFeatureProvider>().First());
if (mareConfig.GetValue<Uri>(nameof(ServerConfiguration.MainServerAddress), defaultValue: null) == null) if (mareConfig.GetValue<Uri>(nameof(ServerConfiguration.MainServerAddress), defaultValue: null) == null)
{ {
a.FeatureProviders.Add(new AllowedControllersFeatureProvider(typeof(MareServerConfigurationController), typeof(MareAuthBaseConfigurationController), typeof(JwtController))); a.FeatureProviders.Add(new AllowedControllersFeatureProvider(typeof(MareServerConfigurationController), typeof(MareAuthBaseConfigurationController), typeof(JwtController), typeof(ClientMessageController)));
} }
else else
{ {
@@ -288,8 +286,6 @@ public class Startup
{ {
services.AddSingleton<IConfigurationService<ServerConfiguration>, MareConfigurationServiceServer<ServerConfiguration>>(); services.AddSingleton<IConfigurationService<ServerConfiguration>, MareConfigurationServiceServer<ServerConfiguration>>();
services.AddSingleton<IConfigurationService<MareConfigurationAuthBase>, MareConfigurationServiceServer<MareConfigurationAuthBase>>(); services.AddSingleton<IConfigurationService<MareConfigurationAuthBase>, MareConfigurationServiceServer<MareConfigurationAuthBase>>();
services.AddGrpc();
} }
} }
@@ -321,11 +317,6 @@ public class Startup
options.Transports = HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling; options.Transports = HttpTransportType.WebSockets | HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling;
}); });
if (config.IsMain)
{
endpoints.MapGrpcService<GrpcClientMessageService>().AllowAnonymous();
}
endpoints.MapHealthChecks("/health").AllowAnonymous(); endpoints.MapHealthChecks("/health").AllowAnonymous();
endpoints.MapControllers(); endpoints.MapControllers();

View File

@@ -8,9 +8,8 @@ using Prometheus;
using MareSynchronosShared.Models; using MareSynchronosShared.Models;
using MareSynchronosShared.Utils; using MareSynchronosShared.Utils;
using MareSynchronosShared.Services; using MareSynchronosShared.Services;
using Grpc.Net.ClientFactory;
using MareSynchronosShared.Protos;
using StackExchange.Redis; using StackExchange.Redis;
using MareSynchronos.API.Data.Enum;
namespace MareSynchronosServices.Discord; namespace MareSynchronosServices.Discord;
@@ -30,21 +29,19 @@ public class MareModule : InteractionModuleBase
private readonly DiscordBotServices _botServices; private readonly DiscordBotServices _botServices;
private readonly IConfigurationService<ServerConfiguration> _mareClientConfigurationService; private readonly IConfigurationService<ServerConfiguration> _mareClientConfigurationService;
private readonly IConfigurationService<ServicesConfiguration> _mareServicesConfiguration; private readonly IConfigurationService<ServicesConfiguration> _mareServicesConfiguration;
private readonly GrpcClientFactory _grpcClientFactory;
private readonly IConnectionMultiplexer _connectionMultiplexer; private readonly IConnectionMultiplexer _connectionMultiplexer;
private Random random = new(); private Random random = new();
public MareModule(ILogger<MareModule> logger, IServiceProvider services, DiscordBotServices botServices, public MareModule(ILogger<MareModule> logger, IServiceProvider services, DiscordBotServices botServices,
IConfigurationService<ServerConfiguration> mareClientConfigurationService, IConfigurationService<ServerConfiguration> mareClientConfigurationService,
IConfigurationService<ServicesConfiguration> mareServicesConfiguration, IConfigurationService<ServicesConfiguration> mareServicesConfiguration,
GrpcClientFactory grpcClientFactory, IConnectionMultiplexer connectionMultiplexer) IConnectionMultiplexer connectionMultiplexer)
{ {
_logger = logger; _logger = logger;
_services = services; _services = services;
_botServices = botServices; _botServices = botServices;
_mareClientConfigurationService = mareClientConfigurationService; _mareClientConfigurationService = mareClientConfigurationService;
_mareServicesConfiguration = mareServicesConfiguration; _mareServicesConfiguration = mareServicesConfiguration;
_grpcClientFactory = grpcClientFactory;
_connectionMultiplexer = connectionMultiplexer; _connectionMultiplexer = connectionMultiplexer;
} }
@@ -352,7 +349,7 @@ public class MareModule : InteractionModuleBase
[SlashCommand("message", "ADMIN ONLY: sends a message to clients")] [SlashCommand("message", "ADMIN ONLY: sends a message to clients")]
public async Task SendMessageToClients([Summary("message", "Message to send")] string message, public async Task SendMessageToClients([Summary("message", "Message to send")] string message,
[Summary("severity", "Severity of the message")] MareSynchronosShared.Protos.MessageType messageType = MareSynchronosShared.Protos.MessageType.Info, [Summary("severity", "Severity of the message")] MessageSeverity messageType = MessageSeverity.Information,
[Summary("uid", "User ID to the person to send the message to")] string? uid = null) [Summary("uid", "User ID to the person to send the message to")] string? uid = null)
{ {
_logger.LogInformation("SlashCommand:{userId}:{Method}:{message}:{type}:{uid}", Context.Interaction.User.Id, nameof(SendMessageToClients), message, messageType, uid); _logger.LogInformation("SlashCommand:{userId}:{Method}:{message}:{type}:{uid}", Context.Interaction.User.Id, nameof(SendMessageToClients), message, messageType, uid);
@@ -374,13 +371,10 @@ public class MareModule : InteractionModuleBase
try try
{ {
var client = _grpcClientFactory.CreateClient<ClientMessageService.ClientMessageServiceClient>("MessageClient"); using HttpClient c = new HttpClient();
await client.SendClientMessageAsync(new ClientMessage() await c.PostAsJsonAsync(new Uri(_mareServicesConfiguration.GetValue<Uri>
{ (nameof(ServicesConfiguration.MainServerAddress)), "/msgc/sendMessage"), new ClientMessage(messageType, message, uid ?? string.Empty))
Message = message, .ConfigureAwait(false);
Type = messageType,
Uid = uid ?? string.Empty
});
var discordChannelForMessages = _mareServicesConfiguration.GetValueOrDefault<ulong?>(nameof(ServicesConfiguration.DiscordChannelForMessages), null); var discordChannelForMessages = _mareServicesConfiguration.GetValueOrDefault<ulong?>(nameof(ServicesConfiguration.DiscordChannelForMessages), null);
if (uid == null && discordChannelForMessages != null) if (uid == null && discordChannelForMessages != null)
@@ -390,9 +384,9 @@ public class MareModule : InteractionModuleBase
{ {
var embedColor = messageType switch var embedColor = messageType switch
{ {
MareSynchronosShared.Protos.MessageType.Info => Color.Blue, MessageSeverity.Information => Color.Blue,
MareSynchronosShared.Protos.MessageType.Warning => new Color(255, 255, 0), MessageSeverity.Warning => new Color(255, 255, 0),
MareSynchronosShared.Protos.MessageType.Error => Color.Red, MessageSeverity.Error => Color.Red,
_ => Color.Blue _ => Color.Blue
}; };

View File

@@ -22,7 +22,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.14.1" /> <PackageReference Include="Discord.Net" Version="3.14.1" />
<PackageReference Include="Grpc.AspNetCore" Version="2.62.0" />
<PackageReference Include="Meziantou.Analyzer" Version="2.0.149"> <PackageReference Include="Meziantou.Analyzer" Version="2.0.149">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

View File

@@ -4,8 +4,6 @@ using MareSynchronosShared.Metrics;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Prometheus; using Prometheus;
using MareSynchronosShared.Utils; using MareSynchronosShared.Utils;
using Grpc.Net.Client.Configuration;
using MareSynchronosShared.Protos;
using MareSynchronosShared.Services; using MareSynchronosShared.Services;
using StackExchange.Redis; using StackExchange.Redis;
using MessagePack.Resolvers; using MessagePack.Resolvers;
@@ -53,12 +51,6 @@ public class Startup
services.AddSingleton(m => new MareMetrics(m.GetService<ILogger<MareMetrics>>(), new List<string> { }, services.AddSingleton(m => new MareMetrics(m.GetService<ILogger<MareMetrics>>(), new List<string> { },
new List<string> { })); new List<string> { }));
var noRetryConfig = new MethodConfig
{
Names = { MethodName.Default },
RetryPolicy = null
};
var redis = mareConfig.GetValue(nameof(ServerConfiguration.RedisConnectionString), string.Empty); var redis = mareConfig.GetValue(nameof(ServerConfiguration.RedisConnectionString), string.Empty);
var options = ConfigurationOptions.Parse(redis); var options = ConfigurationOptions.Parse(redis);
options.ClientName = "Mare"; options.ClientName = "Mare";
@@ -66,18 +58,6 @@ public class Startup
ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(options); ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(options);
services.AddSingleton<IConnectionMultiplexer>(connectionMultiplexer); services.AddSingleton<IConnectionMultiplexer>(connectionMultiplexer);
services.AddGrpcClient<ClientMessageService.ClientMessageServiceClient>("MessageClient", c =>
{
c.Address = new Uri(mareConfig.GetValue<string>(nameof(ServicesConfiguration.MainServerGrpcAddress)));
}).ConfigureChannel(c =>
{
c.ServiceConfig = new ServiceConfig { MethodConfigs = { noRetryConfig } };
c.HttpHandler = new SocketsHttpHandler()
{
EnableMultipleHttp2Connections = true
};
});
var signalRServiceBuilder = services.AddSignalR(hubOptions => var signalRServiceBuilder = services.AddSignalR(hubOptions =>
{ {
hubOptions.MaximumReceiveMessageSize = long.MaxValue; hubOptions.MaximumReceiveMessageSize = long.MaxValue;

View File

@@ -5,10 +5,6 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="Protos\mareservices.proto" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" /> <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup> </ItemGroup>
@@ -20,7 +16,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="ByteSize" Version="2.1.2" /> <PackageReference Include="ByteSize" Version="2.1.2" />
<PackageReference Include="EFCore.NamingConventions" Version="8.0.3" /> <PackageReference Include="EFCore.NamingConventions" Version="8.0.3" />
<PackageReference Include="Grpc.AspNetCore" Version="2.62.0" />
<PackageReference Include="IDisposableAnalyzers" Version="4.0.7"> <PackageReference Include="IDisposableAnalyzers" Version="4.0.7">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -58,9 +53,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Protobuf Include="Protos\mareservices.proto"> <ProjectReference Include="..\..\MareAPI\MareSynchronosAPI\MareSynchronos.API.csproj" />
<GrpcServices>Both</GrpcServices>
</Protobuf>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,23 +0,0 @@
syntax = "proto3";
option csharp_namespace = "MareSynchronosShared.Protos";
package mareservices;
service ClientMessageService {
rpc SendClientMessage (ClientMessage) returns (Empty);
}
message ClientMessage {
MessageType type = 1;
string message = 2;
string uid = 3;
}
enum MessageType {
INFO = 0;
WARNING = 1;
ERROR = 2;
}
message Empty { }

View File

@@ -0,0 +1,4 @@
using MareSynchronos.API.Data.Enum;
namespace MareSynchronosShared.Utils;
public record ClientMessage(MessageSeverity Severity, string Message, string UID);

View File

@@ -7,14 +7,13 @@ public class ServicesConfiguration : MareConfigurationBase
public string DiscordBotToken { get; set; } = string.Empty; public string DiscordBotToken { get; set; } = string.Empty;
public ulong? DiscordChannelForMessages { get; set; } = null; public ulong? DiscordChannelForMessages { get; set; } = null;
public ulong? DiscordChannelForReports { get; set; } = null; public ulong? DiscordChannelForReports { get; set; } = null;
public Uri MainServerGrpcAddress { get; set; } = null;
public override string ToString() public override string ToString()
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.AppendLine(base.ToString()); sb.AppendLine(base.ToString());
sb.AppendLine($"{nameof(DiscordBotToken)} => {DiscordBotToken}"); sb.AppendLine($"{nameof(DiscordBotToken)} => {DiscordBotToken}");
sb.AppendLine($"{nameof(MainServerGrpcAddress)} => {MainServerGrpcAddress}"); sb.AppendLine($"{nameof(MainServerAddress)} => {MainServerAddress}");
sb.AppendLine($"{nameof(DiscordChannelForMessages)} => {DiscordChannelForMessages}"); sb.AppendLine($"{nameof(DiscordChannelForMessages)} => {DiscordChannelForMessages}");
sb.AppendLine($"{nameof(DiscordChannelForReports)} => {DiscordChannelForReports}"); sb.AppendLine($"{nameof(DiscordChannelForReports)} => {DiscordChannelForReports}");
return sb.ToString(); return sb.ToString();