191 lines
9.0 KiB
C#
191 lines
9.0 KiB
C#
using System;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using FinlyticCore.Dtos;
|
|
using FinlyticCore.Models;
|
|
using FinlyticCore.Services;
|
|
using FinlyticCore.Util;
|
|
using FinlyticFundamentals.Database;
|
|
using FinlyticFundamentals.Services;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace FinlyticFundamentals.Util;
|
|
|
|
public class FundamentalsMqttClient : ManagedMqttClient, IHostedService
|
|
{
|
|
private readonly ILogger<FundamentalsMqttClient> _logger;
|
|
private readonly IConfiguration _configuration;
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
|
|
public FundamentalsMqttClient(
|
|
ILogger<FundamentalsMqttClient> logger,
|
|
IConfiguration configuration,
|
|
IServiceScopeFactory scopeFactory) : base(logger)
|
|
{
|
|
_logger = logger;
|
|
_configuration = configuration;
|
|
_scopeFactory = scopeFactory;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
var config = new MqttConfiguration
|
|
{
|
|
Host = _configuration["MQTT:Host"] ?? _configuration["MQTT__Host"] ?? "localhost",
|
|
Port = Convert.ToInt32(_configuration["MQTT:Port"] ?? _configuration["MQTT__Port"] ?? "1883"),
|
|
ClientId = _configuration["MQTT:ClientId"] ?? "finlytic_fundamentals_" + Guid.NewGuid().ToString("N")
|
|
};
|
|
|
|
_logger.LogInformation("[{Channel}] [MQTT_Client] Starting Fundamentals MQTT client. Host: {Host}, ClientId: {ClientId}", "MqttChannel", config.Host, config.ClientId);
|
|
|
|
await ConnectAsync(config);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("[{Channel}] [MQTT_Client] Stopping Fundamentals MQTT client.", "MqttChannel");
|
|
await DisconnectAsync();
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override async Task OnConnectedAsync()
|
|
{
|
|
_logger.LogInformation("[{Channel}] [MQTT_Client] Connected. Subscribing to RPC request topics...", "MqttChannel");
|
|
await SubscribeAsync("services/request/fundamentals_Get/#");
|
|
await SubscribeAsync("services/request/events_GetAll/#");
|
|
await SubscribeAsync("services/request/events_GetByMonth/#");
|
|
await SubscribeAsync("services/request/health_Ping/#");
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override async Task OnMessageReceivedAsync(string topic, string payload)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(topic)) return;
|
|
|
|
var lastSlash = topic.LastIndexOf('/');
|
|
if (lastSlash < 0 || lastSlash >= topic.Length - 1) return;
|
|
|
|
var correlationId = topic.Substring(lastSlash + 1);
|
|
|
|
if (topic.StartsWith("services/request/fundamentals_Get", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await OnFundamentalsGetAsync(payload, correlationId);
|
|
}
|
|
else if (topic.StartsWith("services/request/events_GetAll", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await OnEventsGetAllAsync(correlationId);
|
|
}
|
|
else if (topic.StartsWith("services/request/events_GetByMonth", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await OnEventsGetByMonthAsync(payload, correlationId);
|
|
}
|
|
else if (topic.StartsWith("services/request/health_Ping", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await OnHealthPingAsync(topic, correlationId);
|
|
}
|
|
}
|
|
|
|
private async Task OnFundamentalsGetAsync(string payload, string correlationId)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var finlyticLogger = scope.ServiceProvider.GetRequiredService<IFinlyticLogger<FundamentalsMqttClient, FundamentalsDbContext>>();
|
|
var dbService = scope.ServiceProvider.GetRequiredService<IFundamentalsDbService>();
|
|
|
|
if (string.IsNullOrWhiteSpace(payload))
|
|
{
|
|
await finlyticLogger.LogWarningAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Received empty payload for fundamentals_Get request.");
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var request = (IsinRequest?)JsonSerializer.Deserialize(payload, typeof(IsinRequest), FinlyticJsonSerializerContext.Default);
|
|
if (request == null || string.IsNullOrWhiteSpace(request.Isin))
|
|
{
|
|
await finlyticLogger.LogWarningAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Request missing mandatory ISIN parameter in payload.");
|
|
return;
|
|
}
|
|
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Processing RPC fundamentals_Get for ISIN '{Isin}' (forceRefresh={ForceRefresh}) [CorrelationId: {CorrelationId}]",
|
|
request.Isin, request.ForceRefresh.ToString(), correlationId);
|
|
|
|
var fundamentals = await dbService.GetFundamentalsAsync(request.Isin, request.Ticker, request.ForceRefresh);
|
|
var responseTopic = $"services/response/fundamentals_Get/{correlationId}";
|
|
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Publishing RPC fundamentals response to '{ResponseTopic}'", responseTopic);
|
|
await PublishAsync(responseTopic, fundamentals);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await finlyticLogger.LogErrorAsync(SettingKeys.MqttChannel, ex, "[FinlyticFundamentals] [MQTT_Client] Failed to process fundamentals_Get request.");
|
|
}
|
|
}
|
|
|
|
private async Task OnEventsGetAllAsync(string correlationId)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var finlyticLogger = scope.ServiceProvider.GetRequiredService<IFinlyticLogger<FundamentalsMqttClient, FundamentalsDbContext>>();
|
|
var dbService = scope.ServiceProvider.GetRequiredService<IFundamentalsDbService>();
|
|
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Processing RPC events_GetAll request [CorrelationId: {CorrelationId}]", correlationId);
|
|
try
|
|
{
|
|
var events = await dbService.GetAllEventsAsync();
|
|
var responseTopic = $"services/response/events_GetAll/{correlationId}";
|
|
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Publishing events RPC response to '{ResponseTopic}'", responseTopic);
|
|
await PublishAsync(responseTopic, events);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await finlyticLogger.LogErrorAsync(SettingKeys.MqttChannel, ex, "[FinlyticFundamentals] [MQTT_Client] Failed to process events_GetAll request.");
|
|
}
|
|
}
|
|
|
|
private async Task OnEventsGetByMonthAsync(string payload, string correlationId)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(payload)) return;
|
|
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var finlyticLogger = scope.ServiceProvider.GetRequiredService<IFinlyticLogger<FundamentalsMqttClient, FundamentalsDbContext>>();
|
|
var dbService = scope.ServiceProvider.GetRequiredService<IFundamentalsDbService>();
|
|
|
|
try
|
|
{
|
|
var request = (GetEventsByMonthRequest?)JsonSerializer.Deserialize(payload, typeof(GetEventsByMonthRequest), FinlyticJsonSerializerContext.Default);
|
|
if (request == null) return;
|
|
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Processing RPC events_GetByMonth request for {Year}/{Month} [CorrelationId: {CorrelationId}]", request.Year, request.Month, correlationId);
|
|
|
|
var events = await dbService.GetEventsByMonthAsync(request.Year, request.Month);
|
|
var responseTopic = $"services/response/events_GetByMonth/{correlationId}";
|
|
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.MqttChannel, "[FinlyticFundamentals] [MQTT_Client] Publishing monthly events RPC response to '{ResponseTopic}'", responseTopic);
|
|
await PublishAsync(responseTopic, events);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await finlyticLogger.LogErrorAsync(SettingKeys.MqttChannel, ex, "[FinlyticFundamentals] [MQTT_Client] Failed to process events_GetByMonth request.");
|
|
}
|
|
}
|
|
|
|
private async Task OnHealthPingAsync(string topic, string correlationId)
|
|
{
|
|
if (topic.Contains("FinlyticFundamentals", StringComparison.OrdinalIgnoreCase) || !topic.Contains("/", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var finlyticLogger = scope.ServiceProvider.GetRequiredService<IFinlyticLogger<FundamentalsMqttClient, FundamentalsDbContext>>();
|
|
|
|
var respTopic = $"services/response/health_Ping/{correlationId}";
|
|
await PublishAsync(respTopic, new ServiceHealthResponse("FinlyticFundamentals", "Online", DateTime.UtcNow, "Connected"));
|
|
await finlyticLogger.LogInfoAsync(SettingKeys.HealthPingChannel, "[FinlyticFundamentals] [Health_Ping] Responded to live health_Ping RPC request [CorrelationId: {CorrelationId}].", correlationId);
|
|
}
|
|
}
|
|
}
|