| | 1 | | using System.Net; |
| | 2 | | using System.Net.Sockets; |
| | 3 | | using Microsoft.Extensions.Logging; |
| | 4 | | using Microsoft.Extensions.Options; |
| | 5 | |
|
| | 6 | | namespace NLightning.Application.NLTG.Services; |
| | 7 | |
|
| | 8 | | using Domain.Node.Options; |
| | 9 | | using Infrastructure.Node.Interfaces; |
| | 10 | | using Interfaces; |
| | 11 | |
|
| | 12 | | public class TcpListenerService : ITcpListenerService |
| | 13 | | { |
| | 14 | | private readonly ILogger<TcpListenerService> _logger; |
| | 15 | | private readonly NodeOptions _nodeOptions; |
| | 16 | | private readonly IPeerManager _peerManager; |
| 0 | 17 | | private readonly List<TcpListener> _listeners = []; |
| | 18 | |
|
| | 19 | | private CancellationTokenSource? _cts; |
| | 20 | | private Task? _listeningTask; |
| | 21 | |
|
| 0 | 22 | | public TcpListenerService(ILogger<TcpListenerService> logger, IOptions<NodeOptions> nodeOptions, |
| 0 | 23 | | IPeerManager peerManager) |
| | 24 | | { |
| 0 | 25 | | _logger = logger; |
| 0 | 26 | | _nodeOptions = nodeOptions.Value; |
| 0 | 27 | | _peerManager = peerManager; |
| 0 | 28 | | } |
| | 29 | |
|
| | 30 | | public Task StartAsync(CancellationToken cancellationToken) |
| | 31 | | { |
| 0 | 32 | | _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | 33 | |
|
| 0 | 34 | | foreach (var address in _nodeOptions.ListenAddresses) |
| | 35 | | { |
| 0 | 36 | | var parts = address.Split(':'); |
| 0 | 37 | | if (parts.Length != 2 || !int.TryParse(parts[1], out var port)) |
| | 38 | | { |
| 0 | 39 | | _logger.LogWarning("Invalid listen address: {Address}", address); |
| 0 | 40 | | continue; |
| | 41 | | } |
| | 42 | |
|
| 0 | 43 | | var ipAddress = IPAddress.Parse(parts[0]); |
| 0 | 44 | | var listener = new TcpListener(ipAddress, port); |
| 0 | 45 | | listener.Start(); |
| 0 | 46 | | _listeners.Add(listener); |
| | 47 | |
|
| 0 | 48 | | _logger.LogInformation("Listening for connections on {Address}:{Port}", ipAddress, port); |
| | 49 | | } |
| | 50 | |
|
| 0 | 51 | | _listeningTask = ListenForConnectionsAsync(_cts.Token); |
| | 52 | |
|
| 0 | 53 | | return Task.CompletedTask; |
| | 54 | | } |
| | 55 | |
|
| | 56 | | public async Task StopAsync() |
| | 57 | | { |
| 0 | 58 | | if (_cts is null) |
| | 59 | | { |
| 0 | 60 | | throw new InvalidOperationException("Service is not running"); |
| | 61 | | } |
| | 62 | |
|
| 0 | 63 | | await _cts.CancelAsync(); |
| | 64 | |
|
| 0 | 65 | | foreach (var listener in _listeners) |
| | 66 | | { |
| | 67 | | try |
| | 68 | | { |
| 0 | 69 | | listener.Stop(); |
| 0 | 70 | | } |
| 0 | 71 | | catch (Exception ex) |
| | 72 | | { |
| 0 | 73 | | _logger.LogError(ex, "Error stopping listener"); |
| 0 | 74 | | } |
| | 75 | | } |
| | 76 | |
|
| 0 | 77 | | _listeners.Clear(); |
| | 78 | |
|
| 0 | 79 | | if (_listeningTask is not null) |
| | 80 | | { |
| | 81 | | try |
| | 82 | | { |
| 0 | 83 | | await _listeningTask; |
| 0 | 84 | | } |
| 0 | 85 | | catch (OperationCanceledException) |
| | 86 | | { |
| | 87 | | // Expected during cancellation |
| 0 | 88 | | } |
| | 89 | | } |
| 0 | 90 | | } |
| | 91 | |
|
| | 92 | | private async Task ListenForConnectionsAsync(CancellationToken cancellationToken) |
| | 93 | | { |
| | 94 | | try |
| | 95 | | { |
| 0 | 96 | | while (!cancellationToken.IsCancellationRequested) |
| | 97 | | { |
| 0 | 98 | | foreach (var listener in _listeners) |
| | 99 | | { |
| 0 | 100 | | if (!listener.Pending()) |
| | 101 | | { |
| | 102 | | continue; |
| | 103 | | } |
| | 104 | |
|
| 0 | 105 | | var tcpClient = await listener.AcceptTcpClientAsync(cancellationToken); |
| 0 | 106 | | _ = Task.Run(async () => |
| 0 | 107 | | { |
| 0 | 108 | | try |
| 0 | 109 | | { |
| 0 | 110 | | _logger.LogInformation("New peer connection from {RemoteEndPoint}", tcpClient.Client.RemoteE |
| 0 | 111 | | await _peerManager.AcceptPeerAsync(tcpClient); |
| 0 | 112 | | } |
| 0 | 113 | | catch (Exception e) |
| 0 | 114 | | { |
| 0 | 115 | | _logger.LogError(e, "Error accepting peer connection for {RemoteEndPoint}", |
| 0 | 116 | | tcpClient.Client.RemoteEndPoint); |
| 0 | 117 | | } |
| 0 | 118 | | }, cancellationToken); |
| 0 | 119 | | } |
| | 120 | |
|
| 0 | 121 | | await Task.Delay(100, cancellationToken); // Avoid busy-waiting |
| | 122 | | } |
| 0 | 123 | | } |
| 0 | 124 | | catch (OperationCanceledException) |
| | 125 | | { |
| 0 | 126 | | _logger.LogInformation("Stopping listener service"); |
| 0 | 127 | | } |
| 0 | 128 | | catch (Exception e) |
| | 129 | | { |
| 0 | 130 | | _logger.LogError(e, "Unhandled exception in listener service"); |
| 0 | 131 | | } |
| 0 | 132 | | } |
| | 133 | | } |