|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using EntglDb.Core.Network; |
| 5 | +using EntglDb.Network; |
| 6 | +using EntglDb.Services.NodeStatus.Proto; |
| 7 | +using Google.Protobuf; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | + |
| 10 | +namespace EntglDb.Services.NodeStatus; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// Server-side handler that responds to <see cref="NodeStatusMessageType.NodeStatusReq"/> (wire type 1000) |
| 14 | +/// with a snapshot of the local node's runtime status. |
| 15 | +/// </summary> |
| 16 | +/// <remarks> |
| 17 | +/// Register this handler in DI <em>after</em> <c>AddEntglDbNetwork</c>: |
| 18 | +/// <code> |
| 19 | +/// services.AddEntglDbNetwork<MyConfig>(); |
| 20 | +/// services.AddEntglDbNodeStatus(); // registers NodeStatusHandler + INodeStatusService |
| 21 | +/// </code> |
| 22 | +/// </remarks> |
| 23 | +public sealed class NodeStatusHandler : INetworkMessageHandler |
| 24 | +{ |
| 25 | + private readonly IPeerNodeConfigurationProvider _configProvider; |
| 26 | + private readonly IDiscoveryService _discovery; |
| 27 | + private readonly ILogger<NodeStatusHandler> _logger; |
| 28 | + private readonly DateTimeOffset _startTime = DateTimeOffset.UtcNow; |
| 29 | + |
| 30 | + // Assembly version is resolved once at construction time. |
| 31 | + private static readonly string ServiceVersion = |
| 32 | + typeof(NodeStatusHandler).Assembly.GetName().Version?.ToString() ?? "unknown"; |
| 33 | + |
| 34 | + public int MessageType => (int)NodeStatusMessageType.NodeStatusReq; |
| 35 | + |
| 36 | + public NodeStatusHandler( |
| 37 | + IPeerNodeConfigurationProvider configProvider, |
| 38 | + IDiscoveryService discovery, |
| 39 | + ILogger<NodeStatusHandler> logger) |
| 40 | + { |
| 41 | + _configProvider = configProvider; |
| 42 | + _discovery = discovery; |
| 43 | + _logger = logger; |
| 44 | + } |
| 45 | + |
| 46 | + /// <inheritdoc/> |
| 47 | + public async Task<(IMessage? Response, int ResponseType)> HandleAsync(IMessageHandlerContext context) |
| 48 | + { |
| 49 | + var config = await _configProvider.GetConfiguration(); |
| 50 | + |
| 51 | + var activePeers = _discovery.GetActivePeers().ToList(); |
| 52 | + |
| 53 | + var response = new NodeStatusResponse |
| 54 | + { |
| 55 | + NodeId = config.NodeId, |
| 56 | + UptimeSeconds = (long)(DateTimeOffset.UtcNow - _startTime).TotalSeconds, |
| 57 | + KnownPeerCount = activePeers.Count, |
| 58 | + ServiceVersion = ServiceVersion, |
| 59 | + }; |
| 60 | + |
| 61 | + foreach (var peer in activePeers) |
| 62 | + response.KnownPeerAddresses.Add(peer.Address); |
| 63 | + |
| 64 | + _logger.LogDebug("NodeStatus query from {Remote}: responded with {PeerCount} known peers", |
| 65 | + context.RemoteEndPoint, activePeers.Count); |
| 66 | + |
| 67 | + return (response, (int)NodeStatusMessageType.NodeStatusRes); |
| 68 | + } |
| 69 | +} |
0 commit comments