diff --git a/src/NATS.Server/Auth/Account.cs b/src/NATS.Server/Auth/Account.cs index 211f431..8c6ecbe 100644 --- a/src/NATS.Server/Auth/Account.cs +++ b/src/NATS.Server/Auth/Account.cs @@ -48,5 +48,28 @@ public sealed class Account : IDisposable Interlocked.Decrement(ref _subscriptionCount); } + // Per-account message/byte stats + private long _inMsgs; + private long _outMsgs; + private long _inBytes; + private long _outBytes; + + public long InMsgs => Interlocked.Read(ref _inMsgs); + public long OutMsgs => Interlocked.Read(ref _outMsgs); + public long InBytes => Interlocked.Read(ref _inBytes); + public long OutBytes => Interlocked.Read(ref _outBytes); + + public void IncrementInbound(long msgs, long bytes) + { + Interlocked.Add(ref _inMsgs, msgs); + Interlocked.Add(ref _inBytes, bytes); + } + + public void IncrementOutbound(long msgs, long bytes) + { + Interlocked.Add(ref _outMsgs, msgs); + Interlocked.Add(ref _outBytes, bytes); + } + public void Dispose() => SubList.Dispose(); } diff --git a/tests/NATS.Server.Tests/AccountStatsTests.cs b/tests/NATS.Server.Tests/AccountStatsTests.cs new file mode 100644 index 0000000..362dd18 --- /dev/null +++ b/tests/NATS.Server.Tests/AccountStatsTests.cs @@ -0,0 +1,48 @@ +using NATS.Server.Auth; + +namespace NATS.Server.Tests; + +public class AccountStatsTests +{ + [Fact] + public void Account_tracks_inbound_stats() + { + var account = new Account("test"); + account.IncrementInbound(1, 100); + account.IncrementInbound(1, 200); + account.InMsgs.ShouldBe(2); + account.InBytes.ShouldBe(300); + } + + [Fact] + public void Account_tracks_outbound_stats() + { + var account = new Account("test"); + account.IncrementOutbound(1, 50); + account.IncrementOutbound(1, 75); + account.OutMsgs.ShouldBe(2); + account.OutBytes.ShouldBe(125); + } + + [Fact] + public void Account_stats_start_at_zero() + { + var account = new Account("test"); + account.InMsgs.ShouldBe(0); + account.OutMsgs.ShouldBe(0); + account.InBytes.ShouldBe(0); + account.OutBytes.ShouldBe(0); + } + + [Fact] + public void Account_stats_are_independent() + { + var account = new Account("test"); + account.IncrementInbound(5, 500); + account.IncrementOutbound(3, 300); + account.InMsgs.ShouldBe(5); + account.OutMsgs.ShouldBe(3); + account.InBytes.ShouldBe(500); + account.OutBytes.ShouldBe(300); + } +}