|
| 1 | +using System; |
| 2 | +using System.Buffers; |
| 3 | +using System.Collections.Concurrent; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.IO.Pipelines; |
| 6 | +using System.Linq; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.AspNetCore.Connections; |
| 10 | + |
| 11 | +namespace EventStore.ClusterNode.Components.Services; |
| 12 | + |
| 13 | +public sealed class NodeConnectionTracker |
| 14 | +{ |
| 15 | + private readonly ConcurrentDictionary<string, NodeConnectionState> _connections = new(); |
| 16 | + |
| 17 | + public IReadOnlyList<NodeConnectionSnapshot> Snapshot() => |
| 18 | + _connections.Values.Select(x => x.Snapshot()) |
| 19 | + .OrderBy(x => x.RemoteEndPoint, StringComparer.OrdinalIgnoreCase) |
| 20 | + .ThenBy(x => x.ConnectionId, StringComparer.Ordinal) |
| 21 | + .ToArray(); |
| 22 | + |
| 23 | + public async Task Track(ConnectionContext context, ConnectionDelegate next, bool isTls) |
| 24 | + { |
| 25 | + var state = new NodeConnectionState( |
| 26 | + context.ConnectionId, |
| 27 | + context.RemoteEndPoint?.ToString() ?? "", |
| 28 | + context.LocalEndPoint?.ToString() ?? "", |
| 29 | + isTls, |
| 30 | + DateTimeOffset.UtcNow); |
| 31 | + _connections[context.ConnectionId] = state; |
| 32 | + context.Transport = new CountingDuplexPipe(context.Transport, state); |
| 33 | + |
| 34 | + try |
| 35 | + { |
| 36 | + await next(context); |
| 37 | + } |
| 38 | + finally |
| 39 | + { |
| 40 | + _connections.TryRemove(context.ConnectionId, out _); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public void ObserveRequest( |
| 45 | + string connectionId, |
| 46 | + string protocol, |
| 47 | + bool isGrpc, |
| 48 | + string connectionName, |
| 49 | + string userAgent) |
| 50 | + { |
| 51 | + if (_connections.TryGetValue(connectionId, out var connection)) |
| 52 | + connection.ObserveRequest(protocol, isGrpc, connectionName, userAgent); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +public sealed record NodeConnectionSnapshot( |
| 57 | + string ConnectionId, |
| 58 | + string RemoteEndPoint, |
| 59 | + string LocalEndPoint, |
| 60 | + string ClientName, |
| 61 | + string Application, |
| 62 | + string Protocol, |
| 63 | + bool IsTls, |
| 64 | + DateTimeOffset ConnectedAt, |
| 65 | + long TotalBytesSent, |
| 66 | + long TotalBytesReceived, |
| 67 | + long PendingSendBytes, |
| 68 | + long PendingReceivedBytes); |
| 69 | + |
| 70 | +internal sealed class NodeConnectionState |
| 71 | +{ |
| 72 | + private readonly object _metadataLock = new(); |
| 73 | + private string _clientName = ""; |
| 74 | + private bool _hasExplicitConnectionName; |
| 75 | + private bool _hasGrpcRequests; |
| 76 | + private bool _hasHttpRequests; |
| 77 | + private long _pendingReceivedBytes; |
| 78 | + private long _pendingSendBytes; |
| 79 | + private string _protocol = ""; |
| 80 | + private long _totalBytesReceived; |
| 81 | + private long _totalBytesSent; |
| 82 | + |
| 83 | + public NodeConnectionState( |
| 84 | + string connectionId, |
| 85 | + string remoteEndPoint, |
| 86 | + string localEndPoint, |
| 87 | + bool isTls, |
| 88 | + DateTimeOffset connectedAt) |
| 89 | + { |
| 90 | + ConnectionId = connectionId; |
| 91 | + RemoteEndPoint = remoteEndPoint; |
| 92 | + LocalEndPoint = localEndPoint; |
| 93 | + IsTls = isTls; |
| 94 | + ConnectedAt = connectedAt; |
| 95 | + } |
| 96 | + |
| 97 | + private string ConnectionId { get; } |
| 98 | + private string RemoteEndPoint { get; } |
| 99 | + private string LocalEndPoint { get; } |
| 100 | + private bool IsTls { get; } |
| 101 | + private DateTimeOffset ConnectedAt { get; } |
| 102 | + |
| 103 | + public void Received(long bytes, long pendingBytes) |
| 104 | + { |
| 105 | + Interlocked.Add(ref _totalBytesReceived, bytes); |
| 106 | + Interlocked.Exchange(ref _pendingReceivedBytes, pendingBytes); |
| 107 | + } |
| 108 | + |
| 109 | + public void Reading(long pendingBytes) => |
| 110 | + Interlocked.Exchange(ref _pendingReceivedBytes, pendingBytes); |
| 111 | + |
| 112 | + public void Sending(int bytes) |
| 113 | + { |
| 114 | + Interlocked.Add(ref _totalBytesSent, bytes); |
| 115 | + Interlocked.Add(ref _pendingSendBytes, bytes); |
| 116 | + } |
| 117 | + |
| 118 | + public void Sent() => Interlocked.Exchange(ref _pendingSendBytes, 0); |
| 119 | + |
| 120 | + public void ObserveRequest( |
| 121 | + string protocol, |
| 122 | + bool isGrpc, |
| 123 | + string connectionName, |
| 124 | + string userAgent) |
| 125 | + { |
| 126 | + lock (_metadataLock) |
| 127 | + { |
| 128 | + _protocol = Merge(_protocol, protocol); |
| 129 | + _hasGrpcRequests |= isGrpc; |
| 130 | + _hasHttpRequests |= !isGrpc; |
| 131 | + |
| 132 | + if (!string.IsNullOrWhiteSpace(connectionName)) |
| 133 | + { |
| 134 | + _clientName = connectionName; |
| 135 | + _hasExplicitConnectionName = true; |
| 136 | + } |
| 137 | + else if (!_hasExplicitConnectionName && !string.IsNullOrWhiteSpace(userAgent)) |
| 138 | + { |
| 139 | + _clientName = userAgent; |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + public NodeConnectionSnapshot Snapshot() |
| 145 | + { |
| 146 | + lock (_metadataLock) |
| 147 | + { |
| 148 | + return new( |
| 149 | + ConnectionId, |
| 150 | + RemoteEndPoint, |
| 151 | + LocalEndPoint, |
| 152 | + _clientName, |
| 153 | + ApplicationLabel(), |
| 154 | + _protocol, |
| 155 | + IsTls, |
| 156 | + ConnectedAt, |
| 157 | + Interlocked.Read(ref _totalBytesSent), |
| 158 | + Interlocked.Read(ref _totalBytesReceived), |
| 159 | + Interlocked.Read(ref _pendingSendBytes), |
| 160 | + Interlocked.Read(ref _pendingReceivedBytes)); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + private string ApplicationLabel() => (_hasHttpRequests, _hasGrpcRequests) switch |
| 165 | + { |
| 166 | + (true, true) => "HTTP and gRPC", |
| 167 | + (false, true) => "gRPC", |
| 168 | + (true, false) => "HTTP", |
| 169 | + _ => "Awaiting request" |
| 170 | + }; |
| 171 | + |
| 172 | + private static string Merge(string current, string observed) |
| 173 | + { |
| 174 | + if (string.IsNullOrWhiteSpace(observed) || current == observed) |
| 175 | + return current; |
| 176 | + return string.IsNullOrWhiteSpace(current) ? observed : "Mixed"; |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +internal sealed class CountingDuplexPipe : IDuplexPipe |
| 181 | +{ |
| 182 | + public CountingDuplexPipe(IDuplexPipe inner, NodeConnectionState state) |
| 183 | + { |
| 184 | + Input = new CountingPipeReader(inner.Input, state); |
| 185 | + Output = new CountingPipeWriter(inner.Output, state); |
| 186 | + } |
| 187 | + |
| 188 | + public PipeReader Input { get; } |
| 189 | + public PipeWriter Output { get; } |
| 190 | +} |
| 191 | + |
| 192 | +internal sealed class CountingPipeReader : PipeReader |
| 193 | +{ |
| 194 | + private readonly PipeReader _inner; |
| 195 | + private readonly NodeConnectionState _state; |
| 196 | + private ReadOnlySequence<byte> _currentBuffer; |
| 197 | + |
| 198 | + public CountingPipeReader(PipeReader inner, NodeConnectionState state) |
| 199 | + { |
| 200 | + _inner = inner; |
| 201 | + _state = state; |
| 202 | + } |
| 203 | + |
| 204 | + public override void AdvanceTo(SequencePosition consumed) => AdvanceTo(consumed, consumed); |
| 205 | + |
| 206 | + public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) |
| 207 | + { |
| 208 | + var consumedBytes = _currentBuffer.IsEmpty ? 0 : _currentBuffer.Slice(0, consumed).Length; |
| 209 | + var pendingBytes = _currentBuffer.IsEmpty ? 0 : _currentBuffer.Slice(consumed).Length; |
| 210 | + _state.Received(consumedBytes, pendingBytes); |
| 211 | + _currentBuffer = default; |
| 212 | + _inner.AdvanceTo(consumed, examined); |
| 213 | + } |
| 214 | + |
| 215 | + public override void CancelPendingRead() => _inner.CancelPendingRead(); |
| 216 | + |
| 217 | + public override void Complete(Exception exception = null) => _inner.Complete(exception); |
| 218 | + |
| 219 | + public override ValueTask CompleteAsync(Exception exception = null) => _inner.CompleteAsync(exception); |
| 220 | + |
| 221 | + public override async ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default) |
| 222 | + { |
| 223 | + var result = await _inner.ReadAsync(cancellationToken); |
| 224 | + Observe(result); |
| 225 | + return result; |
| 226 | + } |
| 227 | + |
| 228 | + public override bool TryRead(out ReadResult result) |
| 229 | + { |
| 230 | + if (!_inner.TryRead(out result)) |
| 231 | + return false; |
| 232 | + |
| 233 | + Observe(result); |
| 234 | + return true; |
| 235 | + } |
| 236 | + |
| 237 | + private void Observe(ReadResult result) |
| 238 | + { |
| 239 | + _currentBuffer = result.Buffer; |
| 240 | + _state.Reading(result.Buffer.Length); |
| 241 | + } |
| 242 | +} |
| 243 | + |
| 244 | +internal sealed class CountingPipeWriter : PipeWriter |
| 245 | +{ |
| 246 | + private readonly PipeWriter _inner; |
| 247 | + private readonly NodeConnectionState _state; |
| 248 | + |
| 249 | + public CountingPipeWriter(PipeWriter inner, NodeConnectionState state) |
| 250 | + { |
| 251 | + _inner = inner; |
| 252 | + _state = state; |
| 253 | + } |
| 254 | + |
| 255 | + public override void Advance(int bytes) |
| 256 | + { |
| 257 | + _state.Sending(bytes); |
| 258 | + _inner.Advance(bytes); |
| 259 | + } |
| 260 | + |
| 261 | + public override void CancelPendingFlush() => _inner.CancelPendingFlush(); |
| 262 | + |
| 263 | + public override void Complete(Exception exception = null) => _inner.Complete(exception); |
| 264 | + |
| 265 | + public override ValueTask CompleteAsync(Exception exception = null) => _inner.CompleteAsync(exception); |
| 266 | + |
| 267 | + public override async ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default) |
| 268 | + { |
| 269 | + var result = await _inner.FlushAsync(cancellationToken); |
| 270 | + if (!result.IsCanceled) |
| 271 | + _state.Sent(); |
| 272 | + return result; |
| 273 | + } |
| 274 | + |
| 275 | + public override Memory<byte> GetMemory(int sizeHint = 0) => _inner.GetMemory(sizeHint); |
| 276 | + |
| 277 | + public override Span<byte> GetSpan(int sizeHint = 0) => _inner.GetSpan(sizeHint); |
| 278 | +} |
0 commit comments