using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using FinlyticAssets.Entities;
using FinlyticAssets.Services;
using FinlyticCore.Dtos;
using FinlyticCore.Dtos.Assets;
using FinlyticCore.Dtos.Settings;
using FinlyticCore.Dtos.TechnicalAnalysis;
using FinlyticCore.Models;
using FinlyticCore.Models.Assets;
using FinlyticCore.Services;
using FinlyticCore.Services.TradeRepublic;
using FinlyticCore.Util;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace FinlyticAssets.Util;
///
/// Managed MQTT client acting as an RPC provider for asset lookups, discovery, and on-demand derivatives.
///
public class AssetsMqttClient : ManagedMqttClient, IHostedService
{
private readonly ILogger _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly IConfiguration _configuration;
private readonly ConcurrentDictionary _priceCache = new(StringComparer.OrdinalIgnoreCase);
public AssetsMqttClient(
ILogger logger,
IServiceScopeFactory scopeFactory,
IConfiguration configuration) : base(logger)
{
_logger = logger;
_scopeFactory = scopeFactory;
_configuration = configuration;
}
///
/// Starts the MQTT client and connects to the configured broker.
///
public async Task StartAsync(CancellationToken cancellationToken)
{
var config = MqttConfiguration.FromConfiguration(_configuration, "FinlyticAssets");
_logger.LogInformation("Starting Assets MQTT client. Host: {Host}, ClientId: {ClientId}", config.Host, config.ClientId);
await ConnectAsync(config);
}
///
/// Gracefully stops and disconnects the MQTT client.
///
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping Assets MQTT client.");
await DisconnectAsync();
}
///
/// Invoked automatically once the connection to the MQTT broker is successfully established or restored.
///
protected override async Task OnConnectedAsync()
{
_logger.LogInformation("Assets MQTT Client connected. Registering topic subscriptions...");
await SubscribeAsync(MqttTopics.ResponseWildcard);
await SubscribeRpcAsync>(MqttTopics.RequestFilter(MqttTopics.Channels.AssetsGet), HandleAssetsGetRpcAsync);
await SubscribeRpcAsync>(MqttTopics.RequestFilter(MqttTopics.Channels.AssetsGetDiscovery), HandleAssetsGetDiscoveryRpcAsync);
await SubscribeRpcAsync>(MqttTopics.RequestFilter(MqttTopics.Channels.AssetsGetDerivatives), HandleAssetsGetDerivativesRpcAsync);
await SubscribeRpcAsync(MqttTopics.RequestFilter(MqttTopics.Channels.TrGetLivePrice), HandleGetLivePriceRpcAsync);
await SubscribeRpcAsync