65 lines
2.3 KiB
C#
65 lines
2.3 KiB
C#
using Hcs.Broker;
|
|
using Hcs.Broker.Logger;
|
|
using Hcs.Broker.MessageCapturer;
|
|
using Hcs.WebApp.Config;
|
|
using Hcs.WebApp.Services;
|
|
|
|
namespace Hcs.WebApp.BackgroundServices
|
|
{
|
|
public class OperationExecutionService(OperationExecutionState state, IServiceScopeFactory scopeFactory) : BackgroundService
|
|
{
|
|
private const int SLEEP_TIME = 30000;
|
|
|
|
private readonly OperationExecutionState state = state;
|
|
private readonly IServiceScopeFactory scopeFactory = scopeFactory;
|
|
|
|
private Broker.Logger.ILogger logger;
|
|
private IMessageCapturer messageCapturer;
|
|
private IClient client;
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
await InitializeState();
|
|
|
|
InitializeClient();
|
|
|
|
var scope = scopeFactory.CreateScope();
|
|
var operationService = scope.ServiceProvider.GetRequiredService<OperationService>();
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
while (state.TryDequeueOperation(out var operation))
|
|
{
|
|
await operationService.SetOperationMessageGuid(operation.Id, Guid.NewGuid().ToString());
|
|
}
|
|
|
|
await Task.Delay(SLEEP_TIME, stoppingToken);
|
|
}
|
|
}
|
|
|
|
private async Task InitializeState()
|
|
{
|
|
using var scope = scopeFactory.CreateScope();
|
|
var operationService = scope.ServiceProvider.GetRequiredService<OperationService>();
|
|
|
|
var operations = await operationService.GetInitiatedOperations();
|
|
foreach (var operation in operations)
|
|
{
|
|
state.EnqueueOperation(operation);
|
|
}
|
|
}
|
|
|
|
private void InitializeClient()
|
|
{
|
|
logger = new ActionLogger();
|
|
messageCapturer = new FileMessageCapturer("messages", logger);
|
|
|
|
using var scope = scopeFactory.CreateScope();
|
|
var configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
|
|
var config = configuration.GetSection("BrokerConfig").Get<BrokerConfig>()!;
|
|
var clientProvider = scope.ServiceProvider.GetRequiredService<IClientProvider>();
|
|
client = clientProvider.CreateClient(config, logger, messageCapturer);
|
|
}
|
|
}
|
|
}
|