using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog.Context; using System; using System.Threading; using System.Threading.Tasks; namespace ZB.MOM.WW.CBDDC.Network; /// /// Hosted service that automatically starts and stops the CBDDC node. /// public class CBDDCNodeService : IHostedService { private readonly ICBDDCNode _node; private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// The CBDDC node to manage. /// The logger instance. public CBDDCNodeService(ICBDDCNode node, ILogger logger) { _node = node; _logger = logger; } /// /// Starts the managed CBDDC node. /// /// A token used to cancel startup. /// A task that represents the asynchronous start operation. public async Task StartAsync(CancellationToken cancellationToken) { using var serviceContext = LogContext.PushProperty("Service", nameof(CBDDCNodeService)); using var operationContext = LogContext.PushProperty("OperationId", Guid.NewGuid().ToString("N")); using var actionContext = LogContext.PushProperty("Action", "Start"); try { _logger.LogInformation("Starting CBDDC Node Service..."); // Check for cancellation before starting cancellationToken.ThrowIfCancellationRequested(); await _node.Start(); _logger.LogInformation("CBDDC Node Service started successfully"); } catch (OperationCanceledException) { _logger.LogWarning("CBDDC Node Service start was cancelled"); throw; } catch (Exception ex) { _logger.LogError(ex, "Failed to start CBDDC Node Service"); throw; } } /// /// Stops the managed CBDDC node. /// /// A token used to cancel shutdown. /// A task that represents the asynchronous stop operation. public async Task StopAsync(CancellationToken cancellationToken) { using var serviceContext = LogContext.PushProperty("Service", nameof(CBDDCNodeService)); using var operationContext = LogContext.PushProperty("OperationId", Guid.NewGuid().ToString("N")); using var actionContext = LogContext.PushProperty("Action", "Stop"); try { _logger.LogInformation("Stopping CBDDC Node Service..."); await _node.Stop(); _logger.LogInformation("CBDDC Node Service stopped successfully"); } catch (Exception ex) { _logger.LogError(ex, "Error occurred while stopping CBDDC Node Service"); // Don't rethrow during shutdown to avoid breaking the shutdown process } } }