Commit Graph

311 Commits

Author SHA1 Message Date
Joseph Doherty
96db73d1c6 feat: deliver retained messages on MQTT SUBSCRIBE (Gap 6.5)
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.
2026-02-25 11:40:50 -05:00
Joseph Doherty
f069fdc76a feat: add MQTT MaxAckPending flow control (Gap 6.4)
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.
2026-02-25 11:38:47 -05:00
Joseph Doherty
a44ad4b7fc feat: add MQTT will message delivery on abnormal disconnect (Gap 6.2)
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.
2026-02-25 11:38:43 -05:00
Joseph Doherty
18f0ca0587 feat: add consecutive short-read counter to prevent buffer oscillation (Gap 5.10)
Require 4 consecutive short reads before shrinking AdaptiveReadBuffer, matching
the Go server's readLoop behaviour and preventing buffer size thrashing.
2026-02-25 11:36:12 -05:00
Joseph Doherty
bd2504c8df feat: add SUB permission caching with generation invalidation (Gap 5.8)
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.
2026-02-25 11:36:05 -05:00
Joseph Doherty
a6e8088526 test: verify internal client kinds (Gap 5.9) 2026-02-25 11:35:21 -05:00
Joseph Doherty
7e5c6e4fd9 feat: add slow consumer per-kind tracking with account counters (Gap 5.5)
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.
2026-02-25 11:33:58 -05:00
Joseph Doherty
774717d57c feat: add per-client trace delivery and echo control (Gap 5.7)
Implements ClientTraceInfo with TraceMsgDelivery recording and per-client
echo suppression; fixes AccountGoParityTests namespace ambiguity caused by
the new NATS.Server.Tests.Subscriptions test namespace.
2026-02-25 11:32:00 -05:00
Joseph Doherty
bc8f0e63bb feat: add dynamic write buffer pooling with broadcast drain (Gap 5.6)
Enhances OutboundBufferPool with tiered internal pools (512/4096/65536),
RentBuffer/ReturnBuffer raw-array surface, BroadcastDrain coalescing for
fan-out publish, and Interlocked stats counters (RentCount, ReturnCount,
BroadcastCount). Adds 10 DynamicBufferPoolTests covering all new paths.
2026-02-25 11:31:29 -05:00
Joseph Doherty
1a1e99f7d8 feat: add per-account subscription result cache with LRU (Gap 5.4)
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.
2026-02-25 11:31:17 -05:00
Joseph Doherty
0e1a39df96 feat: add source/mirror info reporting for monitoring (Gap 4.10)
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.
2026-02-25 11:26:34 -05:00
Joseph Doherty
5e49006cfa feat: add stream config update validation (Gap 4.8)
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.
2026-02-25 11:25:38 -05:00
Joseph Doherty
79a3ccba4c feat: implement TAR-based stream snapshot with S2 compression (Gap 4.7)
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.
2026-02-25 11:22:25 -05:00
Joseph Doherty
b9f6a8cc0b feat: add cluster-aware pending request tracking for pull consumers (Gap 3.14)
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.
2026-02-25 11:21:21 -05:00
Joseph Doherty
a113dd686d feat: complete source consumer API request generation (Gap 4.3)
Add BuildConsumerCreateRequest, BuildConsumerCreateSubject, and
GetDeliverySequence to SourceCoordinator, modelling Go's
setupSourceConsumer/trySetupSourceConsumer. Covers DeliverPolicy
resume-from-sequence, AckPolicy.None, push/flow-control/heartbeat
consumer fields, and the $JS.API.CONSUMER.CREATE.{name} subject format.
2026-02-25 11:21:21 -05:00
Joseph Doherty
aad9cf17e4 feat: add token bucket rate limiter for consumers (Gap 3.13)
Implements TokenBucketRateLimiter with refill-over-time semantics,
TryConsume/EstimateWait/WaitForTokensAsync API, and dynamic rate updates.
12 tests covering all behaviors including SW004-suppressed refill timing test.
2026-02-25 11:15:58 -05:00
Joseph Doherty
778687cf6f feat: add consumer reset to specific sequence (Gap 3.12)
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.
2026-02-25 11:15:33 -05:00
Joseph Doherty
b9aa62ae99 feat: add sample/observe mode with latency measurement (Gap 3.11)
Implements SampleTracker with stochastic delivery sampling (ParseSampleFrequency,
ShouldSample, RecordLatency) and LatencySample for consumer observability advisories.
Ports consumer.go sampleFrequency / shouldSample / parseSampleFrequency logic.
15 new tests covering parsing, rate extremes, deterministic seeded sampling, and field capture.
2026-02-25 11:14:58 -05:00
Joseph Doherty
8b4b236968 feat: add delivery interest tracking with auto-cleanup (Gap 3.8)
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.
2026-02-25 11:13:06 -05:00
Joseph Doherty
3d721c6ff1 feat: add filter skip tracking using SubjectMatch (Gap 3.10)
Add FilterSkipTracker using SubjectMatch.MatchLiteral() for NATS token-based
filter matching with sorted-set skip sequence gap tracking. Includes 14 tests
covering exact match, star/gt wildcards, multi-filter, counters, RecordSkip,
NextUnskippedSequence, PurgeBelow, and Reset.
2026-02-25 11:12:57 -05:00
Joseph Doherty
5b0283adf4 feat: add max delivery enforcement with advisory generation (Gap 3.9)
Adds MaxDeliver property, exceeded sequence tracking, DrainExceeded,
DeliveryExceededPolicy enum, and ScheduleRedelivery enforcement to
AckProcessor; 10 new tests in MaxDeliveriesTests.cs.
2026-02-25 11:12:49 -05:00
Joseph Doherty
ae4bc1f683 feat: implement core message delivery loop for push consumers (Gap 3.1)
Adds DeliveryLoopTests covering the gather loop's store polling, filter
subject enforcement, NextSequence advancement, deleted-message skipping,
GatheredCount tracking, signal wake-up, and cancellation behaviour.
2026-02-25 11:09:52 -05:00
Joseph Doherty
7611bcc464 feat: add idle heartbeat with pending count headers and flow control stall detection (Gap 3.5)
Heartbeat frames now include Nats-Pending-Messages and Nats-Pending-Bytes
headers populated from the ConsumerHandle. Flow control frames increment
FlowControlPendingCount; AcknowledgeFlowControl() decrements it. IsFlowControlStalled
returns true when pending count reaches MaxFlowControlPending (2).

Go reference: consumer.go:5222 (sendIdleHeartbeat), consumer.go:5495 (sendFlowControl).
2026-02-25 11:05:31 -05:00
Joseph Doherty
0acf59f92a feat: wire snapshot/restore API endpoints (Gap 7.4 stub)
Add HandleSnapshotAsync and HandleRestoreAsync with stream-name validation,
chunk metadata (NumChunks, BlkSize) in the response, and richer error codes.
Add StreamManager.Exists helper. Add JetStreamSnapshot.StreamName/NumChunks/BlkSize
fields. Fix AdvisoryEventTests.cs using-directive ordering. Add 12 SnapshotApiTests.
2026-02-25 10:57:01 -05:00
Joseph Doherty
41604df752 feat: wire consumer pause/resume API endpoint (Gap 7.5)
Enhances HandlePause to parse pause_until (RFC3339) for time-bounded
pauses and returns current pause state in the response body. Adds
Paused/PauseUntil properties and PauseResponse factory to
JetStreamApiResponse. Covers 10 new parity tests.
2026-02-25 10:56:22 -05:00
Joseph Doherty
2c52b69c93 feat: add advisory event publication for API operations (Gap 7.6)
Add JetStream advisory subject constants to EventSubjects and a lightweight
AdvisoryPublisher that publishes stream/consumer lifecycle events to
$JS.EVENT.ADVISORY.* subjects without depending on InternalEventSystem
directly (testable via Action delegate injection).
2026-02-25 10:56:11 -05:00
Joseph Doherty
c0d206102d feat: add API rate limiting and request deduplication (Gap 7.3)
Implements ApiRateLimiter with SemaphoreSlim-based concurrency limiting (default 256 slots)
and ConcurrentDictionary dedup cache keyed by request ID with configurable TTL, matching
Go's jetstream_api.go maxConcurrentRequests semaphore and dedup window. Also adds
ClusteredRequestProcessor for correlating pending RAFT proposals with waiting callers via
TaskCompletionSource, and SlopwatchSuppressAttribute as a marker for intentional timing-based
tests. 12 ApiRateLimiter tests + 13 ClusteredRequestProcessor tests all pass.
2026-02-25 10:51:22 -05:00
Joseph Doherty
f6d024c50d feat: add clustered stream/consumer API handlers (Gap 2.12)
Implement HandleClusteredCreateAsync, HandleClusteredUpdateAsync, and
HandleClusteredDeleteAsync on StreamApiHandlers, and HandleClusteredCreateAsync
and HandleClusteredDeleteAsync on ConsumerApiHandlers. These handlers propose
operations to the meta RAFT group (JetStreamMetaGroup) instead of operating on
the local StreamManager/ConsumerManager, matching the Go jsClusteredStreamRequest
and jsClusteredConsumerRequest patterns (jetstream_cluster.go:7620-8265).

Ten tests in ClusteredApiTests.cs verify: stream create proposes to meta group,
duplicate-stream error, not-leader error (code 10003), stream update, stream
delete, not-found-on-delete, consumer create on stream, consumer-on-missing-stream
error, consumer delete, and not-found consumer delete.
2026-02-25 10:43:49 -05:00
Joseph Doherty
d817d6f7a2 feat: implement leader forwarding for JetStream API (Gap 7.1)
Add ILeaderForwarder interface and DefaultLeaderForwarder, update
JetStreamApiRouter with RouteAsync + ForwardedCount so non-leader nodes
can attempt to forward mutating requests to the meta-group leader before
falling back to a NotLeader error response.
2026-02-25 09:53:50 -05:00
Joseph Doherty
aeeb2e6929 feat: add binary assignment codec with golden fixture tests (Gap 2.10)
Implements AssignmentCodec with JSON serialization for StreamAssignment
and ConsumerAssignment, plus Snappy compression helpers for large payloads.
Adds 12 tests covering round-trips, error handling, compression, and a
golden fixture for format stability.
2026-02-25 09:35:19 -05:00
Joseph Doherty
a7c094d6c1 feat: add unsupported asset handling for mixed-version clusters (Gap 2.11)
Add Version property to StreamAssignment and ConsumerAssignment so future-version
entries from newer cluster peers are gracefully skipped rather than applied incorrectly.
ProcessStreamAssignment and ProcessConsumerAssignment now reject entries with
Version > CurrentVersion (1), incrementing SkippedUnsupportedEntries for operator
visibility. Add MetaEntryType.Unknown with a no-op ApplyEntry handler so unrecognised
RAFT entry types never crash the cluster. Version 0 is treated as current for
backward compatibility with pre-versioned assignments.
2026-02-25 09:22:18 -05:00
Joseph Doherty
f69f9b3220 feat: add RaftGroup lifecycle methods (Gap 2.9)
Implement IsMember, SetPreferred, RemovePeer, AddPeer, CreateRaftGroup
factory, IsUnderReplicated, and IsOverReplicated on RaftGroup. Add 22
RaftGroupLifecycleTests covering all helpers and quorum size calculation.
2026-02-25 08:59:36 -05:00
Joseph Doherty
38ae1f6bea feat: add topology-aware placement with tag enforcement (Gap 2.8)
Extends PlacementEngine.SelectPeerGroup with three new capabilities ported
from jetstream_cluster.go:7212 selectPeerGroup:

- JetStreamUniqueTag enforcement: PlacementPolicy.UniqueTag (e.g. "az")
  ensures no two replicas share the same value for a tag with that prefix,
  matching Go's uniqueTagPrefix / checkUniqueTag logic.
- MaxAssetsPerPeer HA limit: peers at or above their asset ceiling are
  deprioritised (moved to fallback), not hard-excluded, so selection still
  succeeds when no preferred peers remain.
- Weighted scoring: candidates sorted by
  score = AvailableStorage - (CurrentAssets * assetCostWeight)
  (DefaultAssetCostWeight = 1 GiB) replacing the raw-storage sort, with a
  custom weight parameter for testing.

10 new tests in TopologyPlacementTests.cs cover all three features and their
edge cases. All 30 PlacementEngine tests continue to pass.
2026-02-25 08:59:18 -05:00
Joseph Doherty
e5f599f770 feat: add peer management with stream reassignment (Gap 2.4)
Add ProcessAddPeer/ProcessRemovePeer to JetStreamMetaGroup for
peer-driven stream reassignment. Includes AddKnownPeer/RemoveKnownPeer
tracked in a HashSet, RemovePeerFromStream, RemapStreamAssignment with
replacement-peer selection from the known pool, and DesiredReplicas on
RaftGroup for under-replication detection. Go ref: jetstream_cluster.go:2290-2439.
2026-02-25 08:53:05 -05:00
Joseph Doherty
0f8f34afaa feat: add entry application pipeline for meta and stream RAFT groups (Gap 2.7)
Extend ApplyEntry in JetStreamMetaGroup with PeerAdd/PeerRemove dispatch
to the existing Task 12 peer management methods. Add StreamMsgOp (Store,
Remove, Purge) and ConsumerOp (Ack, Nak, Deliver, Term, Progress) enums
plus ApplyStreamMsgOp and ApplyConsumerEntry methods to StreamReplicaGroup.
Extend ApplyCommittedEntriesAsync to parse smsg:/centry: command prefixes
and route to the new apply methods. Add MetaEntryType.PeerAdd/PeerRemove
enum values. 35 new tests in EntryApplicationTests.cs, all passing.
2026-02-25 08:38:21 -05:00
Joseph Doherty
f1f7bfbb51 feat: add ReadIndex for linearizable reads via quorum confirmation (Gap 8.7)
Add ReadIndexAsync() to RaftNode that confirms leader quorum by sending
heartbeat RPCs before returning CommitIndex, avoiding log growth for reads.
Add RaftReadIndexTests.cs with 13 tests covering normal path, non-leader
rejection, partitioned leader timeout, single-node fast path, log stability,
and peer LastContact refresh after heartbeat round.
2026-02-25 08:31:17 -05:00
Joseph Doherty
ae4cc6d613 feat: add randomized election timeout jitter (Gap 8.8)
Add RandomizedElectionTimeout() method to RaftNode returning TimeSpan in
[ElectionTimeoutMinMs, ElectionTimeoutMaxMs) using TotalMilliseconds (not
.Milliseconds component) to prevent synchronized elections after partitions.
Make Random injectable for deterministic testing. Fix SendHeartbeatAsync stub
in NatsRaftTransport and test-local transport implementations to satisfy the
IRaftTransport interface added in Gap 8.7.
2026-02-25 08:30:38 -05:00
Joseph Doherty
5a62100397 feat: add quorum check before proposing entries (Gap 8.6)
Add HasQuorum() to RaftNode that counts peers with LastContact within
2 × ElectionTimeoutMaxMs and returns true only when self + current peers
reaches majority. ProposeAsync now throws InvalidOperationException with
"no quorum" when HasQuorum() returns false, preventing a partitioned
leader from diverging the log. Add 14 tests in RaftQuorumCheckTests.cs
covering single-node, 3-node, 5-node, boundary window, and heartbeat
restore scenarios. Update RaftHealthTests.LastContact_updates_on_successful_replication
to avoid triggering the new quorum guard.
2026-02-25 08:26:37 -05:00
Joseph Doherty
5d3a3c73e9 feat: add leadership transfer via TimeoutNow RPC (Gap 8.4)
- Add RaftTimeoutNowWire: 16-byte wire type [8:term][8:leaderId] with
  Encode/Decode roundtrip, matching Go's sendTimeoutNow wire layout
- Add TimeoutNow(group) subject "$NRG.TN.{group}" to RaftSubjects
- Add SendTimeoutNowAsync to IRaftTransport; implement in both
  InMemoryRaftTransport (synchronous delivery) and NatsRaftTransport
  (publishes to $NRG.TN.{group})
- Add TransferLeadershipAsync(targetId, ct) to RaftNode: leader sends
  TimeoutNow RPC, blocks proposals via _transferInProgress flag, polls
  until target becomes leader or 2x election timeout elapses
- Add ReceiveTimeoutNow(term) to RaftNode: target immediately starts
  election bypassing pre-vote, updates term if sender's term is higher
- Block ProposeAsync with InvalidOperationException during transfer
- 15 tests in RaftLeadershipTransferTests covering wire roundtrip,
  ReceiveTimeoutNow behaviour, proposal blocking, target leadership,
  timeout on unreachable peer, and transfer flag lifecycle
2026-02-25 08:22:39 -05:00
Joseph Doherty
7e0bed2447 feat: add chunk-based snapshot streaming with CRC32 validation (Gap 8.3)
- Add SnapshotChunkEnumerator: IEnumerable<byte[]> that splits snapshot data
  into fixed-size chunks (default 65536 bytes) and computes CRC32 over the
  full payload for integrity validation during streaming transfer
- Add RaftInstallSnapshotChunkWire: 24-byte header + variable data wire type
  encoding [snapshotIndex:8][snapshotTerm:4][chunkIndex:4][totalChunks:4][crc32:4][data:N]
- Extend InstallSnapshotFromChunksAsync with optional expectedCrc32 parameter;
  validates assembled data against CRC32 before applying snapshot state, throwing
  InvalidDataException on mismatch to prevent corrupt state installation
- Fix stub IRaftTransport implementations in test files missing SendTimeoutNowAsync
- Fix incorrect role assertion in RaftLeadershipTransferTests (single-node quorum = 1)
- 15 new tests in RaftSnapshotStreamingTests covering enumeration, reassembly,
  CRC correctness, validation success/failure, and wire format roundtrip
2026-02-25 08:21:36 -05:00
Joseph Doherty
7434844a39 feat: optimize FilteredState and LoadMsg with block-aware search (Gap 1.10)
Add NumFiltered with generation-based result caching, block-range binary
search helpers (FindFirstBlockAtOrAfter, FindBlockForSequence), and
CheckSkipFirstBlock optimization. FilteredState uses the block index to
skip sealed blocks below the requested start sequence. LoadMsg gains an
O(log n) block fallback for cases where _messages does not hold the
sequence. Generation counter incremented on every write/delete/purge to
invalidate NumFiltered cache entries.

Add 18 tests in FileStoreFilterQueryTests covering literal and wildcard
FilteredState, start-sequence filtering across multiple blocks, NumFiltered
basic counts and cache invalidation, LoadMsg block search, and
CheckSkipFirstBlock behaviour.

Also fix pre-existing slopwatch violations in WriteCacheTests.cs: replace
Task.Delay(150)/Task.Delay(5) with TrackWriteAt using explicit past
timestamps, and restructure Dispose to avoid empty catch blocks.

Reference: golang/nats-server/server/filestore.go:3191 (FilteredState),
           golang/nats-server/server/filestore.go:8308 (LoadMsg).
2026-02-25 08:13:52 -05:00
Joseph Doherty
6d754635e7 feat: add bounded write cache with TTL eviction and background flush (Gap 1.8)
Add WriteCacheManager inner class to FileStore with ConcurrentDictionary-based
tracking of per-block write sizes and timestamps, a PeriodicTimer (500ms tick)
background eviction loop, TTL-based expiry, and size-cap enforcement. Add
TrackWrite/TrackWriteAt/EvictBlock/FlushAllAsync/DisposeAsync API. Integrate
into FileStore constructor, AppendAsync, StoreMsg, StoreRawMsg, and RotateBlock.
Add MaxCacheSize/CacheExpiry options to FileStoreOptions. 12 new tests cover
size tracking, TTL eviction, size-cap eviction, flush-all, and integration paths.

Reference: golang/nats-server/server/filestore.go:4443 (setupWriteCache),
           golang/nats-server/server/filestore.go:6148 (expireCache).
2026-02-25 08:12:06 -05:00
Joseph Doherty
cbe41d0efb feat: add SequenceSet for sparse deletion tracking with secure erase (Gap 1.7)
Replace HashSet<ulong> _deleted in MsgBlock with SequenceSet — a sorted-range
list that compresses contiguous deletions into (Start, End) intervals. Adds
O(log n) Contains/Add via binary search on range count, matching Go's avl.SequenceSet
semantics with a simpler implementation.

- Add SequenceSet.cs: sorted-range compressed set with Add/Remove/Contains/Count/Clear
  and IEnumerable<ulong> in ascending order. Binary search for all O(log n) ops.
- Replace HashSet<ulong> _deleted and _skipSequences in MsgBlock with SequenceSet.
- Add secureErase parameter (default false) to MsgBlock.Delete(): when true, payload
  bytes are overwritten with RandomNumberGenerator.Fill() before the delete record is
  written, making original content unrecoverable on disk.
- Update FileStore.DeleteInBlock() to propagate secureErase flag.
- Update FileStore.EraseMsg() to use secureErase: true via block layer instead of
  delegating to RemoveMsg().
- Add SequenceSetTests.cs: 25 tests covering Add, Remove, Contains, Count, range
  compression, gap filling, bridge merges, enumeration, boundary values, round-trip.
- Add FileStoreTombstoneTrackingTests.cs: 12 tests covering SequenceSet tracking in
  MsgBlock, tombstone persistence through RebuildIndex recovery, secure erase
  payload overwrite verification, and FileStore.EraseMsg integration.

Go reference: filestore.go:5267 (removeMsg), filestore.go:5890 (eraseMsg),
              avl/seqset.go (SequenceSet).
2026-02-25 08:02:44 -05:00
Joseph Doherty
646a5eb2ae feat: add atomic file writer with SemaphoreSlim for crash-safe state writes (Gap 1.6)
- Add AtomicFileWriter static helper: writes to {path}.{random}.tmp, flushes,
  then File.Move(overwrite:true) — concurrent-safe via unique temp path per call
- Add _stateWriteLock (SemaphoreSlim 1,1) to FileStore; dispose in both Dispose
  and DisposeAsync paths
- Promote WriteStreamState to async WriteStreamStateAsync using AtomicFileWriter
  under the write lock; FlushAllPending now returns Task
- Update IStreamStore.FlushAllPending signature to Task; fix MemStore no-op impl
- Fix FileStoreCrashRecoveryTests to await FlushAllPending (3 sync→async tests)
- Add 9 AtomicFileWriterTests covering create, no-tmp-remains, overwrite,
  concurrent safety, memory overload, empty data, and large payload
2026-02-25 07:55:33 -05:00
Joseph Doherty
5beeb1b3f6 feat: add checksum validation on MsgBlock read path (Gap 1.5)
Add _lastChecksum field and LastChecksum property to MsgBlock tracking
the XxHash64 checksum of the last written record (Go: msgBlock.lchk,
filestore.go:2204). Capture the checksum from the encoded record trailer
on every Write/WriteAt/WriteSkip call. Read-path validation happens
naturally through the existing MessageRecord.Decode checksum check.
2026-02-25 07:50:03 -05:00
Joseph Doherty
bfe7a71fcd feat(cluster): add implicit route and gateway discovery via INFO gossip
Implements ProcessImplicitRoute and ForwardNewRouteInfoToKnownServers on RouteManager,
and ProcessImplicitGateway on GatewayManager, mirroring Go server/route.go and
server/gateway.go INFO gossip-based peer discovery. Adds ConnectUrls to ServerInfo
and introduces GatewayInfo model. 12 new unit tests in ImplicitDiscoveryTests.
2026-02-25 03:05:35 -05:00
Joseph Doherty
e09835ca70 feat(config): add SIGHUP signal handler and config reload validation
Implements SignalHandler (PosixSignalRegistration for SIGHUP) and
ReloadFromOptionsAsync/ReloadFromOptionsResult on ConfigReloader for
in-memory options comparison without reading a config file.
Ports Go server/signal_unix.go handleSignals and server/reload.go Reload.
2026-02-25 02:54:13 -05:00
Joseph Doherty
b7bac8e68e feat(mqtt): add JetStream-backed session and retained message persistence
Add optional IStreamStore backing to MqttSessionStore and MqttRetainedStore,
enabling session and retained message state to survive process restarts via
JetStream persistence. Includes ConnectAsync/SaveSessionAsync for session
lifecycle, SetRetainedAsync/GetRetainedAsync with cleared-topic tombstone
tracking, and 4 new parity tests covering persist/restart/clear semantics.
2026-02-25 02:42:02 -05:00
Joseph Doherty
7468401bd0 feat(client): add write timeout recovery with per-kind policies
Add WriteTimeoutPolicy enum, FlushResult record struct, and
GetWriteTimeoutPolicy static method as nested types in NatsClient.
Models Go's client.go per-kind timeout handling: CLIENT kind closes
on timeout, ROUTER/GATEWAY/LEAF use TCP-level flush recovery.
2026-02-25 02:37:48 -05:00
Joseph Doherty
494d327282 feat(client): add stall gate backpressure for slow consumers
Adds StallGate nested class inside NatsClient that blocks producers when
the outbound buffer exceeds 75% of maxPending capacity, modelling Go's
stc channel and stalledRoute handling in server/client.go.
2026-02-25 02:35:57 -05:00