Replace ConcurrentQueue<ClosedClient> with ClosedConnectionRingBuffer — a
fixed-size ring buffer that overwrites oldest entries when full, eliminating
the manual dequeue-to-cap loop. Adds TotalClosed lifetime counter, GetRecent(),
and Clear(). Wires the ring buffer into NatsServer including capacity resize
on config reload. Adds 10 unit tests covering capacity, ordering, wrapping,
TotalClosed tracking, and Clear behavior.
Add TraceContextPropagator and TraceContext to Internal/MessageTraceContext.cs
for Nats-Trace-Parent header injection and extraction across server hops.
Also add ConnzSortOption/ConnzSorter stubs to fix pre-existing build errors
in Monitoring/Connz.cs. Covered by 10 new tests in TraceContextPropagationTests.cs.
Add ConnzConnectionInfo, ConnzFilterResult, ConnzFilterOptions, and
ConnzFilter static class to Connz.cs, providing a pure unit-testable
layer for account-scoped filtering and pagination that mirrors the Go
server's /connz ?acc= query-parameter behaviour. Ten new tests in
ConnzAccountFilterTests.cs cover FilterByAccount (match, no-match,
case-insensitive), ConnzFilterOptions.Parse (acc param, defaults,
offset/limit), and ApplyFilters (account filter, offset, limit,
no-filter pass-through).
Implements ServiceImportShadowed, GetShadowedServiceImports, HasShadowedImports,
and CheckServiceImportShadowing on Account to detect when local SubList subscriptions
would intercept messages before a service import can receive them. Adds ShadowCheckResult
record and 10 tests covering exact, wildcard, and gt-wildcard shadowing scenarios.
Add ActivationClaim and ActivationCheckResult types plus five methods on
Account (RegisterActivation, CheckActivationExpiry, IsActivationExpired,
GetExpiredActivations, RemoveExpiredActivations) and an ActiveActivationCount
property, mirroring Go accounts.go checkActivation / activationExpired logic.
Adds 10 targeted tests in Auth/ActivationExpirationTests.cs (all pass).
Add ExpiresAt, IsExpired, TimeToExpiry, SetExpiration, ClearExpiration,
SetExpirationFromTtl, and GetExpirationInfo to Account. Expiry is stored
as UTC ticks in a long field (long.MinValue sentinel) for lock-free reads
via Interlocked. Add AccountExpirationInfo record. 10 new tests cover all
behaviours.
Implements CheckJetStreamMigrate, GetActiveJetStreamDomains,
IsJetStreamDomainInUse, and JetStreamEnabledConnectionCount on
LeafNodeManager. Adds JetStreamMigrationResult/JetStreamMigrationStatus
result types. Ten unit tests cover all validation paths (10/10 pass).
Implements WebSocketStreamAdapter — a Stream subclass that wraps
System.Net.WebSockets.WebSocket for use by LeafConnection. Handles
message framing (per-message receive/send), tracks BytesRead/BytesWritten
and MessagesRead/MessagesWritten counters, and exposes IsConnected. Ten
NSubstitute-based unit tests cover all capability flags, delegation, and
telemetry (10/10 pass).
Add SupportsPooling/IsLegacyRoute properties to RouteConnection and
GetLegacyRoute/GetLegacyRoutes/HasLegacyRoutes to RouteManager. Update
GetRouteForAccount to fall back to legacy routes when no dedicated or
pool-capable route is available, matching Go route.go getRoutesExcludePool.
Add SetPermissions/PermsSynced/AllowedPublishSubjects/AllowedSubscribeSubjects/AccountName
to LeafConnection, and SendPermsAndAccountInfo/InitLeafNodeSmapAndSendSubs/GetPermSyncStatus
plus LeafPermSyncResult to LeafNodeManager. Add OnConnectionRegistered internal callback for
test synchronization. 10 new unit tests in LeafPermissionSyncTests.cs all passing.
Adds ValidateRemoteLeafNode to LeafNodeManager with self-connect,
duplicate-connection, and JetStream domain conflict checks, plus
IsSelfConnect, HasConnection, and GetConnectionByRemoteId helpers.
Introduces LeafValidationResult and LeafValidationError types.
Adds 10 unit tests in LeafValidationTests covering all error codes.
Add UpdateTlsConfig to LeafNodeManager with CurrentCertPath, CurrentKeyPath,
IsTlsEnabled, and TlsReloadCount. Add LeafTlsReloadResult record. Add 10 unit
tests in LeafTlsReloadTests covering change detection, no-op idempotency, path
tracking, counter semantics, and result payload.
Add NegotiatePoolSize static method and NegotiatedPoolSize property to
RouteConnection, and ConfiguredPoolSize / GetEffectivePoolSize to
RouteManager. Includes 14 tests covering negotiation semantics, backward
compatibility (zero means no pooling), default state, and deterministic
pool index computation.
Add RemoveRoute, RemoveAllRoutesExcept, RegisterRoute (internal), and
DetectClusterSplit to RouteManager with ClusterSplitResult record, plus
10 tests covering partition detection and route removal behavior.
Add _accountRoutes ConcurrentDictionary to RouteManager with full
CRUD API: RegisterAccountRoute, UnregisterAccountRoute,
GetDedicatedAccountRoute, HasDedicatedRoute,
GetAccountsWithDedicatedRoutes, and DedicatedRouteCount property.
Update GetRouteForAccount to check dedicated routes before falling
back to pool-based selection. Add 10 unit tests in AccountRouteTests.
Adds GatewayConnectionState enum, GatewayRegistration record with atomic
message counters, and a full registry API on GatewayManager: RegisterGateway,
UpdateState, GetRegistration, GetAllRegistrations, UnregisterGateway,
GetConnectedGatewayCount, IncrementMessagesSent, IncrementMessagesReceived.
Covers 11 new tests in GatewayRegistrationTests.cs (all passing).
Add ReplyMapCache to ReplyMapper.cs — an LRU cache with TTL expiration
for gateway reply subject mappings, avoiding repeated string parsing on
the hot path. Includes 10 unit tests covering LRU eviction, TTL expiry,
hit/miss counters, PurgeExpired, and Count.
Adds GatewayReconnectPolicy with exponential backoff and jitter, and
reconnect attempt tracking (GetReconnectAttempts, ResetReconnectAttempts,
ReconnectGatewayAsync) to GatewayManager. 10 new tests cover delay
calculation, cap behaviour, jitter, and per-gateway counter isolation.
Adds per-account subscription tracking to GatewayConnection via
AddAccountSubscription/RemoveAccountSubscription/GetAccountSubscriptions/
AccountSubscriptionCount, with corresponding SendAccountSubscriptions and
GetAccountSubscriptions helpers on GatewayManager. Covered by 10 new unit tests.
Adds LoggingChangeResult and ApplyLoggingChanges to ConfigReloader, deriving
an effective log level from Debug/Trace flags (Trace > Debug > Information) and
reporting flag-level and level-string changes for hot-reload notification.
Add ApplyJetStreamConfigChanges to ConfigReloader for detecting MaxMemoryStore,
MaxFileStore, and Domain changes during hot reload. Add Domain property to
JetStreamOptions. Port 10 unit tests covering all change permutations.
Adds ClusterConfigChangeResult and ApplyClusterConfigChanges to ConfigReloader,
comparing route/gateway/leaf URL sets between old and new NatsOptions and reporting
added/removed routes for connection reconciliation on hot reload.
Add PropagateAuthChanges to ConfigReloader that compares Users, Accounts,
and Authorization token between old and new NatsOptions, returning an
AuthChangeResult describing which auth fields changed for connection re-evaluation.
Add FlapperState class and per-client exponential backoff tracking to
MqttSessionStore. New TrackConnectDisconnect(string) overload returns
FlapperState with backoff level and expiry; IsFlapper, GetBackoffMs,
ClearFlapperState, and CheckAndClearStableClients give callers full
visibility and cleanup control. Legacy two-arg overload preserved for
backward compatibility. Ten unit tests cover counting, threshold,
exponential growth, 60s cap, window reset, and stable-client sweep.
Add DeliverRetainedOnSubscribe to MqttRetainedStore, which iterates
GetMatchingRetained and fires a callback with (topic, payload, qos,
retain=true) for each match. Add 11 unit tests covering exact-match,
'+' single-level, '#' multi-level, no-match, cross-level rejection,
callback arguments, return count, and empty-store behaviour.
Implements MqttFlowController with per-subscription SemaphoreSlim-based
slot tracking for QoS 1/2 messages. Replaces the previous catch-and-swallow
pattern with an explicit CurrentCount guard on Release. 10 unit tests added.
Adds WillMessage class, SetWill/ClearWill/GetWill methods to MqttSessionStore,
PublishWillMessage that dispatches via OnPublish delegate (or tracks as delayed
when DelayIntervalSeconds > 0), and 10 unit tests covering all will message behaviors.
Require 4 consecutive short reads before shrinking AdaptiveReadBuffer, matching
the Go server's readLoop behaviour and preventing buffer size thrashing.
Extend PermissionLruCache with SetSub/TryGetSub (internal key prefix "S:")
alongside existing PUB API ("P:" prefix, backward-compatible). Add Invalidate()
and Generation property for generation-based cache invalidation. Add
GenerationId/IncrementGeneration to Account for account-level change signalling.
10 new tests in SubPermissionCacheTests cover all paths.
Adds SlowConsumerTracker class for per-ClientKind slow consumer counting
with configurable threshold callbacks, and extends Account with atomic
IncrementSlowConsumers/SlowConsumerCount/ResetSlowConsumerCount members.
Includes 10 unit tests covering concurrency, threshold firing, and reset.
Implements ClientTraceInfo with TraceMsgDelivery recording and per-client
echo suppression; fixes AccountGoParityTests namespace ambiguity caused by
the new NATS.Server.Tests.Subscriptions test namespace.
Implements RouteResultCache with fixed-capacity LRU eviction and atomic
generation-based invalidation (Go ref: client.go routeCache, maxResultCacheSize=8192).
Fixes AccountGoParityTests namespace ambiguity introduced by new test file.
Add GetMirrorInfo/GetSourceInfo methods to MirrorCoordinator and
SourceCoordinator returning structured MirrorInfoResponse/SourceInfoResponse
records (Name, Lag, Active ms, FilterSubject, Error). Wire both into
StreamManager.GetMirrorInfo and GetSourceInfos for the monitoring API path.
Add ValidateConfigUpdate to StreamManager with immutability rules for storage type,
mirror, sources, and retention policy; sealed stream guard; MaxConsumers decrease
prevention; even-replica rejection; and subject overlap detection against peer streams.
Wire the check into CreateOrUpdate for all update paths. 12 new tests in
ConfigUpdateValidationTests.cs cover all rules including the StreamManager integration test.
Enhance StreamSnapshotService with CreateTarSnapshotAsync / RestoreTarSnapshotAsync
methods that produce a Snappy-compressed TAR archive (stream.json + messages/*.json).
Add CreateTarSnapshotWithDeadlineAsync for deadline-bounded snapshots, and a
SnapshotRestoreResult record carrying stats. 10 new unit tests in
JetStream/Snapshots/StreamSnapshotTests.cs exercise the full create/restore
round-trip, compression format, empty-stream edge case, and deadline enforcement.
Adds ProposeWaitingRequest, RegisterClusterPending, RemoveClusterPending,
GetClusterPendingRequests, and ClusterPendingCount to PullConsumerEngine,
backed by a ConcurrentDictionary keyed by reply subject. Includes 10 xUnit
tests covering quorum checks, pending tracking, and concurrent access patterns.
Add ResetToSequence to ConsumerManager that updates NextSequence,
clears AckProcessor state via new ClearAll(), and zeroes PendingBytes.
Add AckProcessor.SetAckFloor() that prunes pending entries below the
new floor. Go reference: consumer.go:4241 processResetReq.
Implements DeliveryInterestTracker (consumer.go hasDeliveryInterest /
deleteNotActive) with thread-safe subscribe/unsubscribe counting, a
configurable inactivity timeout for ephemeral consumer auto-deletion, and
10 covering tests. Also adds SlopwatchSuppress to a pre-existing
Task.Delay in MaxDeliveriesTests.cs that was already testing time-based expiry.