-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdist_memory.go
More file actions
4885 lines (4055 loc) · 148 KB
/
dist_memory.go
File metadata and controls
4885 lines (4055 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package backend
import (
"context"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"hash"
"hash/fnv"
"log/slog"
"math/big"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/goccy/go-json"
"github.com/hyp3rd/ewrap"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
metricnoop "go.opentelemetry.io/otel/metric/noop"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
"github.com/hyp3rd/hypercache/internal/cluster"
"github.com/hyp3rd/hypercache/internal/eventbus"
"github.com/hyp3rd/hypercache/internal/sentinel"
cache "github.com/hyp3rd/hypercache/pkg/cache/v2"
)
// distTracerName is the OpenTelemetry instrumentation-library name for
// dist-backend spans. Stable, package-qualified — operators can grep
// span streams by it without depending on individual span names.
const distTracerName = "github.com/hyp3rd/hypercache/pkg/backend"
// Internal tuning constants.
const (
defaultDistShardCount = 8 // default number of shards
listPrealloc = 32 // pre-allocation size for List results
)
// Merkle internal tuning constants & errors.
const (
defaultMerkleChunkSize = 128
merklePreallocEntries = 256
merkleVersionBytes = 8
shiftPerByte = 8 // bit shift per byte when encoding uint64
)
var errNoTransport = ewrap.New("no transport")
// DistMemory is a sharded in-process distributed-like backend. It simulates
// distribution by consistent hashing across a fixed set of in-memory shards.
// It is intended for single-process multi-shard experimentation; NOT cross-process.
type DistMemory struct {
shards []*distShard
shardCount int
capacity int // logical global capacity (0 = unlimited). Not strictly enforced yet.
localNode *cluster.Node
membership *cluster.Membership
ring *cluster.Ring
// eventBus broadcasts topology changes (`members`, `heartbeat`)
// to in-process subscribers — primarily the management HTTP
// server's SSE endpoint. Nil-safe: methods on *eventbus.Bus
// panic on nil receiver, so we always construct one in
// initMembershipIfNeeded even when the bus has no subscribers
// yet (publish to a no-subscriber bus is a no-op).
eventBus *eventbus.Bus
// transport holds the active DistTransport behind an atomic.Pointer so that
// callers (including the hint-replay goroutine) can read it without racing
// against SetTransport / WithDistTransport / lazy HTTP server bring-up.
// Use loadTransport() / storeTransport() instead of touching this directly.
transport atomic.Pointer[distTransportSlot]
httpServer *distHTTPServer // optional internal HTTP server
metrics distMetrics
// chaos (optional) wraps the configured transport with fault injection
// for resilience testing. Set via WithDistChaos; nil in production.
// storeTransport applies the wrapper transparently when chaos is set,
// so the rest of the code path is unaware of the chaos surface.
chaos *Chaos
// repairQueue (optional) coalesces read-repair fan-out across the
// read path. Set via WithDistReadRepairBatch with interval > 0;
// nil means repairs dispatch synchronously inline (the historical
// behavior). repairRemoteReplica checks this field on every call
// and routes accordingly.
repairQueue *repairQueue
// repairBatchInterval + repairBatchSize hold the option values
// captured at construction so the queue is built once with the
// final config after all options have been applied. Zero
// interval means batching is disabled.
repairBatchInterval time.Duration
repairBatchSize int
// configuration (static for now, future: dynamic membership/gossip)
replication int
virtualNodes int
nodeAddr string
nodeID string
seeds []string // static seed node addresses
// heartbeat / failure detection. Phase E added SWIM
// self-refutation (refuteIfSuspected) and HTTP gossip
// dissemination, retiring the prior "experimental" marker —
// the path now disseminates suspect/dead transitions across
// the cluster and lets a falsely-accused node bump its
// incarnation to clear suspicion.
hbInterval time.Duration
hbSuspectAfter time.Duration
hbDeadAfter time.Duration
stopCh chan struct{}
// heartbeat sampling (Phase 2)
hbSampleSize int // number of random peers to probe each tick (0=probe all)
// indirectProbeK is the number of relay peers asked to probe a
// target when the direct probe fails. SWIM-style filter for
// caller-side network blips: the target is only marked suspect if
// every relay also fails to reach it. 0 disables — direct probe
// alone decides liveness, matching the pre-Phase-B behavior.
indirectProbeK int
// indirectProbeTimeout caps how long the per-relay probe call may
// block. Defaults to half the heartbeat interval; tunable via
// WithDistIndirectProbes for clusters with high inter-node RTT.
indirectProbeTimeout time.Duration
// consistency / versioning (initial)
readConsistency ConsistencyLevel
writeConsistency ConsistencyLevel
versionCounter atomic.Uint64 // global monotonic for this node (lamport-like)
// hinted handoff
hintTTL time.Duration
hintReplayInt time.Duration
hintMaxPerNode int
hintMaxTotal int // global cap on total queued hints (0 = unlimited)
hintMaxBytes int64 // approximate total bytes cap across all hints (0 = unlimited)
hintsMu sync.Mutex
hints map[string][]hintedEntry // nodeID -> queue
hintTotal int // current total hints queued (under hintsMu)
hintBytes int64 // approximate bytes of queued hints (under hintsMu)
hintStopCh chan struct{}
// parallel reads
parallelReads bool
// simple gossip
gossipInterval time.Duration
gossipStopCh chan struct{}
// anti-entropy
merkleChunkSize int // number of keys per leaf chunk (power-of-two recommended)
listKeysMax int // cap for fallback ListKeys pulls (0 = unlimited)
// periodic merkle auto-sync
autoSyncInterval time.Duration
autoSyncStopCh chan struct{}
autoSyncPeersPerInterval int // limit number of peers synced per tick (0=all)
lastAutoSyncDuration atomic.Int64 // nanoseconds of last full loop
lastAutoSyncError atomic.Value // error string or nil
// adaptive backoff: when enabled (autoSyncMaxBackoffFactor > 1), the
// auto-sync loop doubles its sleep after each tick that found zero
// divergence across all peers, capped at autoSyncMaxBackoffFactor.
// Any tick that pulls keys resets the factor to 1 immediately.
autoSyncMaxBackoffFactor int // 0/1 = disabled
autoSyncBackoffFactor atomic.Int64 // current multiplier; >=1 when adaptive enabled
autoSyncCleanTicks atomic.Int64 // cumulative clean ticks (whole-cycle, not per-peer)
// tombstone version source when no prior item exists (monotonic per process)
tombVersionCounter atomic.Uint64
// tombstone retention / compaction
tombstoneTTL time.Duration
tombstoneSweepInt time.Duration
tombStopCh chan struct{}
// originalConfig retains the originating configuration (if constructed via config constructor)
originalConfig any
// latency histograms for core ops (Phase 1)
latency *distLatencyCollector
// rebalancing (Phase 3)
rebalanceInterval time.Duration
rebalanceBatchSize int
rebalanceMaxConcurrent int
rebalanceStopCh chan struct{}
lastRebalanceVersion atomic.Uint64
// httpLimits caps inbound request bodies (server) and inbound response
// bodies (auto-created client) plus tunes timeouts and concurrency.
// Zero-valued fields fall back to defaultDistHTTP* in
// dist_http_server.go via DistHTTPLimits.withDefaults().
httpLimits DistHTTPLimits
// httpAuth configures bearer-token / signing-fn auth applied to both
// the dist HTTP server (inbound validation) and the auto-created
// HTTP client (outbound signing). Zero-value disables auth — same
// behavior as before WithDistHTTPAuth was added.
httpAuth DistHTTPAuth
// lifeCtx is the server-lifetime context. Derived from the
// constructor ctx but with its own cancel func wired into Stop, so
// in-flight HTTP handlers and replica forwards observe Done() when
// the user calls Stop — not just when the constructor ctx happens
// to cancel (which it usually doesn't, since callers pass
// context.Background()).
lifeCtx context.Context //nolint:containedctx // server-lifecycle, not request-scope
lifeCancel context.CancelFunc
// replica-only diff scan limits
replicaDiffMaxPerTick int // 0 = unlimited
// shedding / cleanup of keys we no longer own (grace period before delete to aid late reads / hinted handoff)
removalGracePeriod time.Duration // if >0 we delay deleting keys we no longer own; after grace we remove locally
// stopped guards Stop() against double-invocation (idempotent shutdown).
stopped atomic.Bool
// draining is set by Drain to mark this node for graceful shutdown:
// /health returns 503, Set/Remove reject with sentinel.ErrDraining,
// Get continues to serve. One-way — operators restart the process
// to clear it. The CAS in Drain ensures the metric increment fires
// exactly once per drain transition.
draining atomic.Bool
// tracer is the OpenTelemetry tracer used to create spans on the
// public Get/Set/Remove ops and on replication fan-out. Defaults
// to noop.NewTracerProvider so library code emits no spans unless
// the caller opts in via WithDistTracerProvider. The noop tracer's
// Span values are zero-allocation, so the always-on instrumentation
// is cheap on the hot path when tracing is disabled.
tracer trace.Tracer
// meter is the OpenTelemetry meter used to register observable
// counters/gauges that mirror the in-process distMetrics atomics.
// Defaults to noop.NewMeterProvider so library code emits no
// metrics unless the caller opts in via WithDistMeterProvider.
// metricRegistration retains the registration handle returned by
// meter.RegisterCallback so Stop can unregister cleanly — without
// it the SDK would keep invoking the callback after shutdown.
meter metric.Meter
metricRegistration metric.Registration
// logger is the structured logger used by background loops
// (heartbeat, hint replay, rebalance, gossip, merkle sync) and
// error surfaces (transport bind failures, sync errors, dropped
// hints). Defaults to a no-op handler writing to io.Discard so
// library code does not write to stderr unless the caller opts
// in via WithDistLogger. All log lines are pre-bound with
// `node_id` so operators can grep/filter without the call sites
// having to weave the ID through every record.
logger *slog.Logger
}
const (
defaultRebalanceBatchSize = 128
defaultRebalanceMaxConcurrent = 2
)
var errUnexpectedBackendType = ewrap.New("backend: unexpected backend type") // stable error (no dynamic wrapping needed)
// distTransportSlot wraps a DistTransport interface value so it can be stored
// in atomic.Pointer (atomic.Pointer requires a concrete pointer type).
type distTransportSlot struct{ t DistTransport }
// hintedEntry represents a deferred replica write.
type hintedEntry struct {
item *cache.Item
queuedAt time.Time
expire time.Time
size int64 // approximate bytes for global cap accounting
source hintSource // why this hint exists (replication fan-out vs rebalance migration)
}
// hintSource records why a hint landed in the queue. Used to split
// the aggregate hint counters (which sum across both sources) into a
// migration-only view for operators tracking ownership-transfer
// liveness during rebalance phases. Replication-only counts are derivable
// as (aggregate - migration); we don't expose a third metric for it.
type hintSource int8
const (
// hintSourceReplication marks hints produced by a failed write fan-out
// to a peer replica. This is the historical default — every hint
// landed in this bucket before migration-source tagging existed.
hintSourceReplication hintSource = iota
// hintSourceMigration marks hints produced by a rebalance tick that
// could not deliver an item to its new primary owner.
hintSourceMigration
)
// tombstone marks a delete intent with version ordering to prevent resurrection.
type tombstone struct {
version uint64
origin string
at time.Time
}
// ConsistencyLevel defines read/write consistency semantics.
type ConsistencyLevel int
const (
// ConsistencyOne returns after a single owner success (fast, may be stale).
ConsistencyOne ConsistencyLevel = iota
// ConsistencyQuorum waits for majority (floor(n/2)+1).
ConsistencyQuorum
// ConsistencyAll waits for all owners.
ConsistencyAll
)
// String returns the human-readable form for logs and span attributes.
// Unknown values render as `consistency(<int>)` rather than panicking
// so a corrupted/forwards-compatible value still produces useful telemetry.
func (l ConsistencyLevel) String() string {
switch l {
case ConsistencyOne:
return "ONE"
case ConsistencyQuorum:
return "QUORUM"
case ConsistencyAll:
return "ALL"
default:
return "consistency(" + strconv.Itoa(int(l)) + ")"
}
}
// WithDistReadConsistency sets read consistency (default ONE).
func WithDistReadConsistency(l ConsistencyLevel) DistMemoryOption {
return func(dm *DistMemory) { dm.readConsistency = l }
}
// WithDistWriteConsistency sets write consistency (default QUORUM).
func WithDistWriteConsistency(l ConsistencyLevel) DistMemoryOption {
return func(dm *DistMemory) { dm.writeConsistency = l }
}
// WithDistTombstoneTTL configures how long tombstones are retained before subject to compaction (<=0 keeps indefinitely).
func WithDistTombstoneTTL(d time.Duration) DistMemoryOption {
return func(dm *DistMemory) { dm.tombstoneTTL = d }
}
// WithDistTombstoneSweep sets sweep interval for tombstone compaction (<=0 disables automatic sweeps).
func WithDistTombstoneSweep(interval time.Duration) DistMemoryOption {
return func(dm *DistMemory) { dm.tombstoneSweepInt = interval }
}
// Membership returns current membership reference (read-only usage).
func (dm *DistMemory) Membership() *cluster.Membership { return dm.membership }
// Ring returns the ring reference.
func (dm *DistMemory) Ring() *cluster.Ring { return dm.ring }
// LifecycleContext returns the server-lifecycle context derived from the
// ctx supplied to NewDistMemory. Stop cancels this context, so callers
// (including HTTP handlers and background loops) can observe shutdown
// without polling the various stopCh channels. Read-only — modifying
// the returned ctx has no effect.
func (dm *DistMemory) LifecycleContext() context.Context { return dm.lifeCtx }
type distShard struct {
items cache.ConcurrentMap
tombs map[string]tombstone // per-key tombstones
originalPrimary map[string]cluster.NodeID // recorded primary owner at first insert
originalPrimaryMu sync.RWMutex // guards originalPrimary
originalOwners map[string][]cluster.NodeID // recorded full owner set at first insert (for replica diff)
originalOwnersMu sync.RWMutex // guards originalOwners
removedAt map[string]time.Time // when we first observed we are no longer an owner (for grace shedding)
removedAtMu sync.Mutex // guards removedAt
}
// DistMemoryOption configures DistMemory backend.
type DistMemoryOption func(*DistMemory)
// WithDistShardCount sets number of shards (min 1).
func WithDistShardCount(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.shardCount = n
}
}
}
// WithDistMerkleChunkSize sets the number of keys per leaf hash chunk (default 128 if 0).
func WithDistMerkleChunkSize(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.merkleChunkSize = n
}
}
}
// WithDistMerkleAutoSync enables periodic anti-entropy sync attempts. If interval <= 0 disables.
func WithDistMerkleAutoSync(interval time.Duration) DistMemoryOption {
return func(dm *DistMemory) {
dm.autoSyncInterval = interval
}
}
// WithDistMerkleAdaptiveBackoff enables adaptive scheduling for the Merkle
// anti-entropy loop. When maxFactor > 1, the loop doubles its sleep
// interval (1×, 2×, 4×, 8×, …) after each tick that found zero divergence
// across every peer, capped at maxFactor. Any tick with at least one
// dirty peer resets the factor to 1 on the next sleep — recovery is
// always immediate, never lazy.
//
// maxFactor <= 1 disables backoff (the default): the loop wakes at every
// `WithDistMerkleAutoSync` interval regardless of recent divergence.
//
// The current factor is exposed as `dist.auto_sync.backoff_factor` and
// the cumulative count of clean ticks as `dist.auto_sync.clean_ticks`.
// Each factor change is logged once at Info; no per-tick spam.
func WithDistMerkleAdaptiveBackoff(maxFactor int) DistMemoryOption {
return func(dm *DistMemory) {
if maxFactor < 1 {
maxFactor = 0
}
dm.autoSyncMaxBackoffFactor = maxFactor
}
}
// WithDistMerkleAutoSyncPeers limits number of peers synced per interval (0 or <0 = all).
func WithDistMerkleAutoSyncPeers(n int) DistMemoryOption {
return func(dm *DistMemory) {
dm.autoSyncPeersPerInterval = n
}
}
// WithDistListKeysCap caps number of keys fetched via fallback ListKeys (0 = unlimited).
func WithDistListKeysCap(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n >= 0 {
dm.listKeysMax = n
}
}
}
// WithDistRebalanceInterval enables periodic ownership rebalancing checks (<=0 disables).
func WithDistRebalanceInterval(d time.Duration) DistMemoryOption {
return func(dm *DistMemory) {
dm.rebalanceInterval = d
}
}
// WithDistRebalanceBatchSize sets max keys per transfer batch.
func WithDistRebalanceBatchSize(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.rebalanceBatchSize = n
}
}
}
// WithDistRebalanceMaxConcurrent limits concurrent batch transfers.
func WithDistRebalanceMaxConcurrent(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.rebalanceMaxConcurrent = n
}
}
}
// WithDistReplicaDiffMaxPerTick limits number of replica-diff replication operations performed per rebalance tick (0 = unlimited).
func WithDistReplicaDiffMaxPerTick(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.replicaDiffMaxPerTick = n
}
}
}
// WithDistRemovalGrace sets grace period before shedding data for keys we no longer own (<=0 immediate remove disabled for now).
func WithDistRemovalGrace(d time.Duration) DistMemoryOption {
return func(dm *DistMemory) {
if d > 0 {
dm.removalGracePeriod = d
}
}
}
// --- Merkle tree anti-entropy structures ---
// MerkleTree represents a binary hash tree over key/version pairs.
type MerkleTree struct { // minimal representation
LeafHashes [][]byte // ordered leaf hashes
Root []byte
ChunkSize int
}
// BuildMerkleTree constructs a Merkle tree snapshot of local data (best-effort, locks each shard briefly).
func (dm *DistMemory) BuildMerkleTree() *MerkleTree {
chunkSize := dm.merkleChunkSize
if chunkSize <= 0 {
chunkSize = defaultMerkleChunkSize
}
entries := dm.merkleEntries()
if len(entries) == 0 {
return &MerkleTree{ChunkSize: chunkSize}
}
slices.SortFunc(entries, func(a, b merkleKV) int {
return strings.Compare(a.k, b.k)
})
hasher := sha256.New()
buf := make([]byte, merkleVersionBytes)
leaves := make([][]byte, 0, (len(entries)+chunkSize-1)/chunkSize)
for i := 0; i < len(entries); i += chunkSize {
end := min(i+chunkSize, len(entries))
hasher.Reset()
for _, e := range entries[i:end] {
_, _ = hasher.Write([]byte(e.k))
encodeUint64BigEndian(buf, e.v)
_, _ = hasher.Write(buf)
}
leaves = append(leaves, append([]byte(nil), hasher.Sum(nil)...))
}
root := foldMerkle(leaves, hasher)
return &MerkleTree{LeafHashes: leaves, Root: append([]byte(nil), root...), ChunkSize: chunkSize}
}
// merkleKV is an internal pair used during tree construction & sync.
type merkleKV struct {
k string
v uint64
}
// DiffLeafRanges compares two trees and returns indexes of differing leaf chunks.
func (mt *MerkleTree) DiffLeafRanges(other *MerkleTree) []int {
if mt == nil || other == nil {
return nil
}
if len(mt.LeafHashes) != len(other.LeafHashes) { // size mismatch -> full resync
idxs := make([]int, len(mt.LeafHashes))
for i := range idxs {
idxs[i] = i
}
return idxs
}
var diffs []int
for i := range mt.LeafHashes {
if !equalBytes(mt.LeafHashes[i], other.LeafHashes[i]) {
diffs = append(diffs, i)
}
}
return diffs
}
func equalBytes(a, b []byte) bool { // tiny helper
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// SyncWith performs Merkle anti-entropy against a remote node (pull newer versions for differing chunks).
//
// Returns nil even when the local and remote trees agree (a "clean" sync).
// Callers that need to distinguish clean from dirty cycles — currently only
// the adaptive auto-sync backoff path — use syncWithStatus directly.
func (dm *DistMemory) SyncWith(ctx context.Context, nodeID string) error {
_, err := dm.syncWithStatus(ctx, nodeID)
return err
}
// WithDistCapacity sets logical capacity (not strictly enforced yet).
func WithDistCapacity(capacity int) DistMemoryOption {
return func(dm *DistMemory) { dm.capacity = capacity }
}
// WithDistMembership injects an existing membership and (optionally) a local node for multi-node tests.
// If node is nil a new one will be created.
func WithDistMembership(m *cluster.Membership, node *cluster.Node) DistMemoryOption {
return func(dm *DistMemory) {
if m != nil {
dm.membership = m
dm.localNode = node
}
}
}
// WithDistTransport sets a transport used for forwarding / replication.
func WithDistTransport(t DistTransport) DistMemoryOption {
return func(dm *DistMemory) { dm.storeTransport(t) }
}
// WithDistHeartbeatSample sets how many random peers to probe per heartbeat tick (0=all).
func WithDistHeartbeatSample(k int) DistMemoryOption {
return func(dm *DistMemory) { dm.hbSampleSize = k }
}
// SetTransport sets the transport post-construction (testing helper).
func (dm *DistMemory) SetTransport(t DistTransport) { dm.storeTransport(t) }
// WithDistHeartbeat configures heartbeat interval and suspect/dead thresholds.
// If interval <= 0 heartbeat is disabled.
func WithDistHeartbeat(interval, suspectAfter, deadAfter time.Duration) DistMemoryOption {
return func(dm *DistMemory) {
dm.hbInterval = interval
dm.hbSuspectAfter = suspectAfter
dm.hbDeadAfter = deadAfter
}
}
// WithDistIndirectProbes enables SWIM-style indirect probing for the
// heartbeat path. When a direct probe to a peer fails, this node asks
// `k` random alive peers to probe the target on its behalf; the target
// is only marked suspect if every relay also fails. Filters
// caller-side network blips (NIC reset, brief upstream outage, single
// stuck connection in a pool) that would otherwise cause spurious
// suspect/dead transitions.
//
// `timeout` caps each relay's probe call. Pass 0 to inherit the
// default (half the configured heartbeat interval).
//
// k = 0 disables indirect probing — direct probe alone decides
// liveness, matching the pre-Phase-B behavior. Recommended k = 3 for
// production clusters; clusters with fewer than k+1 alive peers scale
// down automatically (probe whatever's available).
func WithDistIndirectProbes(k int, timeout time.Duration) DistMemoryOption {
return func(dm *DistMemory) {
if k < 0 {
k = 0
}
dm.indirectProbeK = k
dm.indirectProbeTimeout = timeout
}
}
// WithDistReplication sets ring replication factor (owners per key).
func WithDistReplication(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.replication = n
}
}
}
// WithDistVirtualNodes sets number of virtual nodes per physical node for consistent hash ring.
func WithDistVirtualNodes(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.virtualNodes = n
}
}
}
// WithDistHintTTL sets TTL for hinted handoff entries.
func WithDistHintTTL(d time.Duration) DistMemoryOption {
return func(dm *DistMemory) { dm.hintTTL = d }
}
// WithDistHintReplayInterval sets how often to attempt replay of hints.
func WithDistHintReplayInterval(d time.Duration) DistMemoryOption {
return func(dm *DistMemory) { dm.hintReplayInt = d }
}
// WithDistHintMaxPerNode caps number of queued hints per target node.
func WithDistHintMaxPerNode(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.hintMaxPerNode = n
}
}
}
// WithDistHintMaxTotal sets a global cap on total queued hints across all nodes.
func WithDistHintMaxTotal(n int) DistMemoryOption {
return func(dm *DistMemory) {
if n > 0 {
dm.hintMaxTotal = n
}
}
}
// WithDistHintMaxBytes sets an approximate byte cap for all queued hints.
func WithDistHintMaxBytes(b int64) DistMemoryOption {
return func(dm *DistMemory) {
if b > 0 {
dm.hintMaxBytes = b
}
}
}
// WithDistParallelReads enables parallel quorum/all read fan-out.
func WithDistParallelReads(enable bool) DistMemoryOption {
return func(dm *DistMemory) { dm.parallelReads = enable }
}
// WithDistGossipInterval enables simple membership gossip at provided interval.
func WithDistGossipInterval(d time.Duration) DistMemoryOption {
return func(dm *DistMemory) { dm.gossipInterval = d }
}
// WithDistNode identity (id optional; derived from address if empty). Address used for future RPC.
func WithDistNode(id, address string) DistMemoryOption {
return func(dm *DistMemory) {
if address != "" {
dm.nodeAddr = address
}
dm.nodeID = id
}
}
// WithDistSeeds configures static seed node addresses.
func WithDistSeeds(addresses []string) DistMemoryOption {
cp := make([]string, 0, len(addresses))
for _, a := range addresses {
if a != "" {
cp = append(cp, a)
}
}
return func(dm *DistMemory) { dm.seeds = cp }
}
// WithDistHTTPLimits configures the HTTP transport limits for the dist
// HTTP server (inbound request bodies, timeouts, concurrency) and the
// auto-created HTTP client (response body cap, request timeout). Partial
// overrides are honored: zero-valued fields inherit the package defaults
// from DistHTTPLimits.withDefaults.
//
// This option only affects the *internal* HTTP server/client created by
// tryStartHTTP — explicitly-supplied transports via WithDistTransport are
// the caller's responsibility to bound.
func WithDistHTTPLimits(limits DistHTTPLimits) DistMemoryOption {
return func(dm *DistMemory) { dm.httpLimits = limits }
}
// WithDistHTTPAuth configures bearer-token (or custom verify/sign)
// authentication for the dist HTTP server and auto-created HTTP client.
// See DistHTTPAuth for the policy struct shape and defaults.
//
// Operators must apply the same auth policy to every node in the
// cluster — peers with mismatched tokens will reject each other's
// requests with HTTP 401. Like WithDistHTTPLimits this only affects the
// internal transport; an externally-supplied DistTransport is the
// caller's responsibility to authenticate.
//
// NewDistMemory validates the resulting policy and returns
// sentinel.ErrInsecureAuthConfig if ClientSign is set without a
// matching inbound verifier (Token or ServerVerify) and
// AllowAnonymousInbound is not set — see DistHTTPAuth for the rationale.
func WithDistHTTPAuth(auth DistHTTPAuth) DistMemoryOption {
return func(dm *DistMemory) { dm.httpAuth = auth }
}
// WithDistLogger supplies a structured logger for the dist backend's
// background loops (heartbeat, hint replay, rebalance, gossip, merkle
// auto-sync) and operational error surfaces (HTTP listener failures,
// transport errors, dropped hints). The supplied logger is wrapped with
// `node_id` and `component=dist_memory` attributes before use, so call
// sites do not need to weave the node ID through every record.
//
// Pass slog.Default() to inherit the application's logger, or supply a
// custom *slog.Logger with the desired level / handler. Zero-value (no
// option call) keeps the dist backend silent — the default uses an
// io.Discard handler, which means library code never writes to stderr
// unless the caller opts in.
//
// nil is treated as "no change" — useful when callers conditionally
// build options.
func WithDistLogger(logger *slog.Logger) DistMemoryOption {
return func(dm *DistMemory) {
if logger != nil {
dm.logger = logger
}
}
}
// WithDistReadRepairBatch enables async coalescing of read-repair
// fan-out. When interval > 0, repairs from the read path are
// queued by destination peer; the queue flushes periodically OR
// when a peer's pending count hits maxBatchSize. Repairs to the
// same (peer, key) collapse to the highest-version entry —
// concurrent reads of the same hot key produce one repair, not N.
//
// Default (interval = 0 or maxBatchSize <= 0): repairs dispatch
// synchronously inside the Get path. Existing callers asserting
// "replica healed by the time Get returns" see byte-identical
// behavior.
//
// Trade-off: batched mode introduces a window (up to `interval`)
// where a divergent replica stays divergent. Merkle anti-entropy
// is the convergence safety net; the read-repair path is and
// always was best-effort. Stop() drains pending entries before
// returning so a clean shutdown doesn't lose queued repairs.
func WithDistReadRepairBatch(interval time.Duration, maxBatchSize int) DistMemoryOption {
return func(dm *DistMemory) {
if interval <= 0 || maxBatchSize <= 0 {
// Out-of-range values disable batching rather than
// silently coercing to a tiny non-zero value the caller
// didn't intend.
dm.repairBatchInterval = 0
dm.repairBatchSize = 0
return
}
dm.repairBatchInterval = interval
dm.repairBatchSize = maxBatchSize
}
}
// WithDistTracerProvider supplies an OpenTelemetry TracerProvider for
// the dist backend. When set, every public Get/Set/Remove call opens a
// span (`dist.get` / `dist.set` / `dist.remove`) carrying consistency
// level and key length attributes; replication fan-out adds child spans
// (`dist.replicate.set` / `dist.replicate.remove`) per peer so operators
// can see where time is spent under load.
//
// Span attributes intentionally omit the cache key value — keys can be
// PII (user IDs, session tokens). Only `cache.key.length` is recorded.
// Callers needing the key value should add their own outer span before
// invoking the dist backend.
//
// Pass otel.GetTracerProvider() to inherit the application's globally
// registered provider, or supply a custom *sdktrace.TracerProvider to
// route dist spans to a dedicated exporter. nil is treated as "no
// change" — useful for conditional option building.
//
// Library default (no option call) installs a no-op tracer, so library
// code emits no spans unless the caller opts in.
func WithDistTracerProvider(tp trace.TracerProvider) DistMemoryOption {
return func(dm *DistMemory) {
if tp != nil {
dm.tracer = tp.Tracer(distTracerName)
}
}
}
// WithDistMeterProvider supplies an OpenTelemetry MeterProvider for the
// dist backend. When set, NewDistMemory registers an observable
// instrument for every field on DistMetrics — counters for cumulative
// totals (writes, forwards, hints, rebalance batches, etc.), gauges for
// current state (active tombstones, hint queue size, alive/suspect/dead
// member counts) and last-operation latencies (merkle build/diff/fetch
// nanoseconds, last rebalance/auto-sync duration). Instrument names use
// the `dist.` prefix so a Prometheus exporter can route them under a
// dedicated subsystem.
//
// A single registered callback drives all instruments: on each
// collection cycle it takes one Metrics() snapshot and observes every
// instrument from that snapshot. There is no per-operation overhead
// when a real meter is configured beyond the existing atomic counters
// the dist backend already maintains.
//
// Pass otel.GetMeterProvider() to inherit the application's globally
// registered provider, or supply a custom MeterProvider built via the
// otel/sdk/metric package (typically wrapping a Prometheus exporter or
// OTLP pipeline). nil is treated as "no change" — useful for
// conditional option building.
//
// Library default (no option call) installs a no-op meter, so library
// code emits no metrics unless the caller opts in.
func WithDistMeterProvider(mp metric.MeterProvider) DistMemoryOption {
return func(dm *DistMemory) {
if mp != nil {
dm.meter = mp.Meter(distTracerName)
}
}
}
// NewDistMemory creates a new DistMemory backend.
func NewDistMemory(ctx context.Context, opts ...DistMemoryOption) (IBackend[DistMemory], error) {
// Derive a server-lifetime context from the caller's ctx so that:
// 1. If the caller cancels their ctx, our background work and HTTP
// handlers see it (chains via WithCancel parent).
// 2. Stop() can independently cancel without touching the caller's
// ctx — gives operators a deterministic shutdown signal even
// when they pass context.Background().
lifeCtx, lifeCancel := context.WithCancel(ctx)
dm := &DistMemory{
shardCount: defaultDistShardCount,
replication: 1,
readConsistency: ConsistencyOne,
writeConsistency: ConsistencyQuorum,
latency: newDistLatencyCollector(),
lifeCtx: lifeCtx,
lifeCancel: lifeCancel,
}
for _, opt := range opts {
opt(dm)
}
// Reject incoherent auth configs (e.g. ClientSign-only) before
// any subsystem captures the policy. validate returns
// sentinel.ErrInsecureAuthConfig for the misconfiguration that
// previously caused silent inbound bypass.
authErr := dm.httpAuth.validate()
if authErr != nil {
lifeCancel()
return nil, authErr
}
dm.installTelemetryDefaults()
dm.ensureShardConfig()
dm.initMembershipIfNeeded()
// Pass the lifecycle ctx to subsystems that capture it (HTTP handlers,
// background loops). The constructor ctx is used only for operations
// that must complete during NewDistMemory itself (e.g. listener bind).
dm.tryStartHTTP(ctx)
dm.logClusterJoin()
dm.startHeartbeatIfEnabled(lifeCtx)
dm.startHintReplayIfEnabled(lifeCtx)
dm.startGossipIfEnabled()
dm.startAutoSyncIfEnabled(lifeCtx)
dm.startTombstoneSweeper()
dm.startRebalancerIfEnabled(lifeCtx)
dm.startRepairQueueIfEnabled(lifeCtx)
return dm, nil
}
// NewDistMemoryWithConfig builds a DistMemory from an external dist.Config shape without introducing a direct import here.
// Accepts a generic 'cfg' to avoid adding a dependency layer; expects exported fields matching internal/dist Config.
func NewDistMemoryWithConfig(ctx context.Context, cfg any, opts ...DistMemoryOption) (IBackend[DistMemory], error) {
type minimalConfig struct { // external mirror subset
NodeID string
BindAddr string
AdvertiseAddr string
Seeds []string
Replication int
VirtualNodes int
ReadConsistency int
WriteConsistency int
HintTTL time.Duration
HintReplay time.Duration
HintMaxPerNode int
}
var mc minimalConfig
if asserted, ok := cfg.(minimalConfig); ok { // best-effort copy
mc = asserted
}
derived := distOptionsFromMinimal(mc)
all := make([]DistMemoryOption, 0, len(derived)+len(opts))
all = append(all, derived...)
all = append(all, opts...)
dmIface, err := NewDistMemory(ctx, all...)
if err != nil {
return nil, err
}
dm, ok := dmIface.(*DistMemory)
if !ok {
return nil, errUnexpectedBackendType
}
dm.originalConfig = cfg
return dm, nil
}
// distOptionsFromMinimal converts a minimalConfig into DistMemoryOptions (pure helper for lint complexity reduction).
func distOptionsFromMinimal(mc struct {
NodeID, BindAddr, AdvertiseAddr string
Seeds []string
Replication, VirtualNodes int
ReadConsistency, WriteConsistency int
HintTTL, HintReplay time.Duration
HintMaxPerNode int