-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapacitor.go
More file actions
3040 lines (2623 loc) · 73.2 KB
/
Copy pathcapacitor.go
File metadata and controls
3040 lines (2623 loc) · 73.2 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 capacitor
import (
"context"
"crypto/sha256"
"crypto/tls"
"errors"
"fmt"
"log"
"math/bits"
"net"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/hashicorp/memberlist"
"github.com/vmihailenco/msgpack/v5"
)
const NoExpiry = time.Duration(-1)
var ErrKeyNotFound = errors.New("capacitor: key not found")
// Logger is a generic structured logging interface.
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
type noopLogger struct{}
func (n noopLogger) Debug(msg string, args ...any) {}
func (n noopLogger) Info(msg string, args ...any) {}
func (n noopLogger) Warn(msg string, args ...any) {}
func (n noopLogger) Error(msg string, args ...any) {}
// Config defines the configuration parameters for a Capacitor node instance.
type Config struct {
// NodeID is the unique identifier for this node in the cluster. If left empty,
// a hostname-based identifier will be generated automatically.
NodeID string
// BindAddr is the network address for the gossip memberlist to bind to.
BindAddr string
// BindPort is the port number utilized for gossip memberlist communications.
BindPort int
// StreamPort is the port number utilized for replication TCP streams.
StreamPort int
// AdvertiseAddr is the IP address advertised to other nodes for establishing
// replication TCP streams.
AdvertiseAddr string
// Peers is the initial list of bootstrap addresses ("IP:port") of active cluster nodes.
Peers []string
// DataPath is the local directory path where BadgerDB files are persistently stored.
DataPath string
// LogSize is the capacity (maximum number of entries) of the in-memory circular Delta Log.
LogSize uint64
// TLSConfig is the optional configuration used to secure node-to-node replication streams using mTLS.
TLSConfig *tls.Config
// AuthToken is a shared secret token used to authenticate gossip join requests and TCP streams.
AuthToken string
// Logger is the structured logging engine injected into the Capacitor instance.
Logger Logger
// DisableMetrics disables internal metrics latency tracking for maximum read/write performance.
DisableMetrics bool
}
// Capacitor represents an active-active, local-first replicated caching node.
// It manages local key-value storage, cluster membership discovery, logical clocks,
// and replication orchestration.
type Capacitor struct {
nodeID string
store *store
hlc *HLC
log *DeltaLog
server *StreamServer
client *StreamClient
ml *memberlist.Memberlist
metrics *MetricsTracker
authToken string
hashedAuthToken string
logger Logger
ctx context.Context
cancel context.CancelFunc
// Replicator state
peerSeqs sync.Map // map[string]uint64 (Last replicated Seq)
peerMutex sync.Mutex
peerStops map[string]peerReplicator
streamAddr string
stop chan struct{}
disableMetrics bool
pubSub *pubSubRegistry
subCounter uint64
replicatorWG sync.WaitGroup
closing uint32 // Atomic flag indicating that the node is closing
}
type peerReplicator struct {
stop chan struct{}
done chan struct{}
}
// New initializes, configures, and starts a local Capacitor node.
// This constructs the storage, starts the replication stream listener, and registers
// the node with the gossip cluster.
func New(cfg Config) (*Capacitor, error) {
if cfg.NodeID == "" {
hostname, _ := os.Hostname()
cfg.NodeID = fmt.Sprintf("%s-%d", hostname, time.Now().Unix())
}
if cfg.LogSize == 0 {
cfg.LogSize = 1_000_000
}
if cfg.Logger == nil {
cfg.Logger = noopLogger{}
}
if cfg.BindPort < 0 || cfg.BindPort > 65535 {
return nil, errors.New("BindPort must be between 0 and 65535")
}
if cfg.StreamPort < 0 || cfg.StreamPort > 65535 {
return nil, errors.New("StreamPort must be between 0 and 65535")
}
bindPort := cfg.BindPort
if bindPort == 0 {
bindPort = 7946
}
if cfg.StreamPort != 0 && cfg.StreamPort == bindPort {
return nil, errors.New("StreamPort and BindPort cannot be the same")
}
if cfg.AuthToken == "" {
cfg.Logger.Warn("AuthToken is empty. Replication stream addresses and node metadata will be transmitted in plaintext via insecure gossip protocols. Do not use this configuration in production.")
}
if cfg.DataPath == "" {
cfg.Logger.Info("DataPath is empty. Running BadgerDB in-memory mode. Data will not persist across restarts.")
}
metrics := NewMetricsTracker()
s, err := newStore(cfg.DataPath, metrics, cfg.Logger)
if err != nil {
metrics.Stop()
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
cp := &Capacitor{
nodeID: cfg.NodeID,
store: s,
hlc: NewHLC(),
log: NewDeltaLog(cfg.LogSize),
client: NewStreamClient(cfg.TLSConfig, cfg.AuthToken, metrics),
metrics: metrics,
stop: make(chan struct{}),
peerStops: make(map[string]peerReplicator),
authToken: cfg.AuthToken,
hashedAuthToken: hashToken(cfg.AuthToken),
logger: cfg.Logger,
ctx: ctx,
cancel: cancel,
disableMetrics: cfg.DisableMetrics,
pubSub: newPubSubRegistry(),
}
srv, err := NewStreamServer(cp, fmt.Sprintf("0.0.0.0:%d", cfg.StreamPort), cfg.TLSConfig)
if err != nil {
return nil, err
}
cp.server = srv
go srv.Start()
// Memberlist config for discovery (initialized early so we can read BindAddr)
mlCfg := memberlist.DefaultLocalConfig()
mlCfg.Name = cfg.NodeID
if cfg.BindAddr != "" {
mlCfg.BindAddr = cfg.BindAddr
}
mlCfg.BindPort = cfg.BindPort
// Secure Gossip layer with AuthToken
if cfg.AuthToken != "" {
hash := sha256.Sum256([]byte(cfg.AuthToken))
mlCfg.SecretKey = hash[:]
}
// Bridge memberlist logging
mlCfg.Logger = log.New(&mlLoggerBridge{cp.logger}, "", 0)
// Determine the actual port bound for the stream server
_, portStr, _ := net.SplitHostPort(srv.listener.Addr().String())
// Determine the address to advertise for TCP streams
advertiseAddr := cfg.AdvertiseAddr
if advertiseAddr == "" {
if mlCfg.BindAddr == "" || mlCfg.BindAddr == "0.0.0.0" || mlCfg.BindAddr == "127.0.0.1" || mlCfg.BindAddr == "localhost" {
if isRunningTests() {
advertiseAddr = "127.0.0.1"
} else {
advertiseAddr = getLocalIP()
}
} else {
advertiseAddr = mlCfg.BindAddr
}
}
cp.streamAddr = net.JoinHostPort(advertiseAddr, portStr)
events := &clusterEvents{cp: cp}
mlCfg.Delegate = events
mlCfg.Events = events
ml, err := memberlist.Create(mlCfg)
if err != nil {
return nil, err
}
cp.ml = ml
if len(cfg.Peers) > 0 {
_, _ = ml.Join(cfg.Peers)
}
return cp, nil
}
type clusterEvents struct {
cp *Capacitor
}
type mlLoggerBridge struct {
l Logger
}
func (m *mlLoggerBridge) Write(p []byte) (n int, err error) {
// Memberlist logs are usually prefixed with [DEBUG], [ERR], etc.
msg := string(p)
switch {
case strings.Contains(msg, "[DEBUG]"):
m.l.Debug(strings.TrimSpace(msg))
case strings.Contains(msg, "[ERR]"):
m.l.Error(strings.TrimSpace(msg))
case strings.Contains(msg, "[WARN]"):
m.l.Warn(strings.TrimSpace(msg))
default:
m.l.Info(strings.TrimSpace(msg))
}
return len(p), nil
}
func (n *clusterEvents) NodeMeta(limit int) []byte {
// Simple handshake: share the address
// In a more complex setup, we could encode a map of LastSeenSeqs here.
// For now, let's just stick to the address and let replicators start from store state.
return []byte(n.cp.streamAddr)
}
func (n *clusterEvents) NotifyMsg([]byte) {}
func (n *clusterEvents) GetBroadcasts(overhead, limit int) [][]byte { return nil }
func (n *clusterEvents) LocalState(join bool) []byte { return nil }
func (n *clusterEvents) MergeRemoteState(buf []byte, join bool) {}
func (n *clusterEvents) NotifyJoin(node *memberlist.Node) {
if node.Name == n.cp.nodeID {
return
}
n.cp.startPeerReplicator(node.Name, string(node.Meta), false)
}
func (n *clusterEvents) NotifyLeave(node *memberlist.Node) {
if n.cp.client != nil {
n.cp.client.CloseConn(node.Name)
}
n.cp.stopPeerReplicator(node.Name)
}
func (n *clusterEvents) NotifyUpdate(node *memberlist.Node) {}
func (f *Capacitor) startPeerReplicator(nodeID, addr string, force bool) {
if addr == "" {
return
}
if atomic.LoadUint32(&f.closing) == 1 {
return
}
f.peerMutex.Lock()
defer f.peerMutex.Unlock()
// If there's an existing replicator, stop it and wait for it to exit
if stopVal, ok := f.peerStops[nodeID]; ok {
if !force {
return
}
close(stopVal.stop)
<-stopVal.done
delete(f.peerStops, nodeID)
}
stop := make(chan struct{})
done := make(chan struct{})
pr := peerReplicator{stop: stop, done: done}
f.peerStops[nodeID] = pr
f.replicatorWG.Add(1)
go func() {
defer f.replicatorWG.Done()
defer close(done)
f.peerReplicatorLoop(nodeID, addr, stop)
}()
}
func (f *Capacitor) stopPeerReplicator(nodeID string) {
f.peerMutex.Lock()
if stopVal, ok := f.peerStops[nodeID]; ok {
close(stopVal.stop)
<-stopVal.done
delete(f.peerStops, nodeID)
}
f.peerMutex.Unlock()
f.log.mu.Lock()
close(f.log.notifyCh)
f.log.notifyCh = make(chan struct{})
f.log.mu.Unlock()
f.peerSeqs.Delete(nodeID)
}
func (f *Capacitor) peerReplicatorLoop(nodeID, addr string, stop chan struct{}) {
defer func() {
if r := recover(); r != nil {
f.logger.Error("panic in peerReplicatorLoop", "error", r, "nodeID", nodeID, "addr", addr)
}
}()
for {
var ch chan struct{}
var lastSeq uint64
f.log.mu.Lock()
for {
select {
case <-stop:
f.log.mu.Unlock()
return
case <-f.ctx.Done():
f.log.mu.Unlock()
return
default:
}
lastSeqVal, ok := f.peerSeqs.Load(nodeID)
if ok && lastSeqVal != nil {
if seq, seqOk := lastSeqVal.(uint64); seqOk {
lastSeq = seq
} else {
lastSeq = f.store.getPeerSeq(nodeID)
}
} else {
lastSeq = f.store.getPeerSeq(nodeID)
}
// head is the next sequence ID to be assigned.
// Entries exist up to head-1.
// If lastSeq is the last one we sent, we want to wait until head > lastSeq + 1.
if f.log.head > lastSeq+1 {
break
}
ch = f.log.notifyCh
f.log.mu.Unlock()
select {
case <-stop:
return
case <-f.ctx.Done():
return
case <-ch:
f.log.mu.Lock()
}
}
f.log.mu.Unlock()
// 2. Perform replication
success := f.replicateToPeer(f.ctx, nodeID, addr)
if !success {
select {
case <-stop:
return
case <-f.ctx.Done():
return
case <-time.After(100 * time.Millisecond):
}
}
}
}
func (f *Capacitor) replicateToPeer(ctx context.Context, nodeID, addr string) bool {
lastSeqVal, _ := f.peerSeqs.LoadOrStore(nodeID, f.store.getPeerSeq(nodeID))
var lastSeq uint64
if lastSeqVal != nil {
if seq, seqOk := lastSeqVal.(uint64); seqOk {
lastSeq = seq
} else {
lastSeq = f.store.getPeerSeq(nodeID)
}
} else {
lastSeq = f.store.getPeerSeq(nodeID)
}
f.log.mu.RLock()
earliest := f.log.earliestSeq
f.log.mu.RUnlock()
if lastSeq+1 < earliest {
f.logger.Warn("Replication gap detected, performing full state bootstrap catch-up", "peer", nodeID, "lastSeq", lastSeq, "earliestSeq", earliest)
snapEntries := f.store.getSnapshotEntries()
const batchSize = 1000
for idx := 0; idx < len(snapEntries); idx += batchSize {
end := idx + batchSize
if end > len(snapEntries) {
end = len(snapEntries)
}
var rawSnap [][]byte
for _, entry := range snapEntries[idx:end] {
bin, _ := entry.MarshalMsg(nil)
rawSnap = append(rawSnap, bin)
}
batch := Batch{
FromNode: f.nodeID,
Entries: rawSnap,
}
repCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
lastSeenRemote := f.store.getPeerSeq(nodeID)
err := f.client.SendBatch(repCtx, nodeID, addr, batch, lastSeenRemote)
cancel()
if err != nil {
f.logger.Error("Full state sync batch send failed", "peer", nodeID, "error", err)
atomic.AddUint64(&f.metrics.ReplicationFailures, 1)
return false
}
}
f.peerSeqs.Store(nodeID, earliest-1)
f.logger.Info("Full state bootstrap catch-up complete, resuming delta replication", "peer", nodeID, "newSeq", earliest-1)
return true
}
// 1. Get new entries from log as raw binary slices
// Hard-limit to 1000 entries OR 8MB per batch for backpressure
rawEntries := f.log.GetEntriesRaw(lastSeq+1, 1000, 8*1024*1024)
if len(rawEntries) == 0 {
return true
}
defer f.log.PutEntriesRaw(rawEntries)
batch := Batch{
FromNode: f.nodeID,
Entries: rawEntries,
}
// 2. Stream to this specific peer
// Pass our LastSeenSeq from them to initiate handshake
lastSeenRemote := f.store.getPeerSeq(nodeID)
// Create a sub-context with timeout for the replication batch
repCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
success := true
if err := f.client.SendBatch(repCtx, nodeID, addr, batch, lastSeenRemote); err == nil {
// Only advance on success
f.peerSeqs.Store(nodeID, lastSeq+uint64(len(rawEntries)))
} else {
atomic.AddUint64(&f.metrics.ReplicationFailures, 1)
success = false
}
return success
}
func (f *Capacitor) applyRemoteEntry(ctx context.Context, e LogEntry, senderNodeID string) {
if senderNodeID != "" && e.Seq > 0 {
lastSeq := f.store.getPeerSeq(senderNodeID)
if int64(e.Seq-lastSeq) <= 0 {
return
}
}
// Track replication latency
if e.BornAt > 0 {
f.metrics.ReplicateLat.Record(time.Since(time.Unix(0, e.BornAt)))
}
// Update local HLC
if _, err := f.hlc.Update(e.TS); err != nil {
// Log clock smash and drop the entry to prevent poisoning
return
}
switch e.Op {
case MsgSet:
var val any
_ = msgpack.Unmarshal(e.Value, &val)
f.store.set(e.Key, val, e.TS, time.Duration(e.TTL)*time.Millisecond)
case MsgIncr:
f.store.setNodeCount(e.Key, e.NodeID, e.Delta)
case MsgMetric:
// Metrics are eventually consistent across nodes
f.store.incrementMetric(e.Key, e.NodeID, e.Delta)
case MsgWindow:
f.store.addWindowTimestamp(e.Key, e.TS.Physical)
case MsgDelete:
f.store.delete(e.Key, e.TS)
case MsgSetAdd:
f.store.setAdd(e.Key, string(e.Value), e.TS)
case MsgSetRemove:
_, _ = f.store.setRemove(e.Key, string(e.Value), e.TS, true)
case MsgSortedSetAdd:
f.store.sortedSetAdd(e.Key, string(e.Value), e.Delta, e.TS)
case MsgSortedSetIncrement:
_, _ = f.store.sortedSetIncrementBy(e.Key, string(e.Value), e.Delta, e.TS)
case MsgSortedSetRemove:
_, _ = f.store.sortedSetRemove(e.Key, string(e.Value), e.TS, true)
case MsgMapSet:
var p MapPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
var ttl time.Duration
if p.ExpiresAt > 0 {
ttl = time.Duration(p.ExpiresAt-time.Now().UnixNano()) * time.Nanosecond
if ttl < 0 {
ttl = 1 * time.Nanosecond
}
}
f.store.mapSet(e.Key, p.Field, p.Value, ttl, e.TS)
}
case MsgMapRemove:
var p MapPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
f.store.mapRemove(e.Key, p.Field, e.TS)
}
case MsgNMapSet:
var p NMapPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
var ttl time.Duration
if p.ExpiresAt > 0 {
ttl = time.Duration(p.ExpiresAt-time.Now().UnixNano()) * time.Nanosecond
if ttl < 0 {
ttl = 1 * time.Nanosecond
}
}
_, _, _, _ = f.store.nmapSet(e.Key, p.Field, p.Value, ttl, e.TS, true)
}
case MsgNMapRemove:
var p NMapPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
_, _, _, _, _ = f.store.nmapRemove(e.Key, p.Field, e.TS, true)
}
case MsgListInsert:
var p ListPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
_, _ = f.store.listInsert(e.Key, p.ID, p.ParentID, p.Value, e.TS)
}
case MsgListDelete:
var p ListPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
_, _ = f.store.listDelete(e.Key, p.ID, e.TS)
}
case MsgHLLAdd:
var p HLLPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
_, _ = f.store.hllAdd(e.Key, p.Index, p.Value, e.TS)
}
case MsgBloomAdd:
var p BloomPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
_, _ = f.store.bloomAdd(e.Key, p.Indices, e.TS)
}
case MsgCMSIncrement:
var p CMSPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
_ = f.store.cmsIncrement(e.Key, p.Element, p.Count, e.TS)
}
case MsgPubSubPublish:
var p PubSubPayload
if err := msgpack.Unmarshal(e.Value, &p); err == nil {
f.pubSub.publish(p.Topic, PubSubMessage{Topic: p.Topic, Payload: p.Payload})
}
}
// Record persistent sequence for catch-up after restart
if senderNodeID != "" && e.Seq > 0 {
f.store.updatePeerSeq(senderNodeID, e.Seq)
}
}
// Set writes a key-value pair to the local store and appends it to the replication
// log to propagate it to other nodes in the cluster. If a positive TTL is specified,
// the key-value pair will automatically expire.
func (f *Capacitor) Set(ctx context.Context, key string, value any, ttl time.Duration) error {
var start time.Time
if !f.disableMetrics {
start = time.Now()
}
// 1. Serialize Once for Log/Replication
binVal, err := msgpack.Marshal(value)
if err != nil {
return err
}
ts := f.hlc.Now()
// 2. Local Write
if err := f.store.set(key, value, ts, ttl); err != nil {
return err
}
// 3. Log Append
f.log.Append(LogEntry{
TS: ts,
BornAt: time.Now().UnixNano(),
Op: MsgSet,
Key: key,
Value: binVal,
TTL: int64(ttl.Milliseconds()),
})
if !f.disableMetrics {
f.metrics.SetLat.Record(time.Since(start))
}
return nil
}
// GetScan retrieves a key's value and unmarshals it into the destination pointer dest
// (similar to json.Unmarshal or database rows.Scan).
func (f *Capacitor) GetScan(ctx context.Context, key string, dest any) error {
var start time.Time
if !f.disableMetrics {
start = time.Now()
}
err := f.getScanInternal(ctx, key, dest)
if !f.disableMetrics {
f.metrics.GetLat.Record(time.Since(start))
}
return err
}
func (f *Capacitor) getScanInternal(ctx context.Context, key string, dest any) error {
rawVal, err := f.store.get(key)
if err != nil {
return err
}
if rawVal == nil {
return fmt.Errorf("capacitor: key %s not found", key)
}
// 1. Reflection-based Direct Assignment Fast Path (In-Memory Hot Path Bypass)
destVal := reflect.ValueOf(dest)
if destVal.Kind() == reflect.Ptr {
elemVal := destVal.Elem()
if elemVal.Type() == reflect.TypeOf(rawVal) {
elemVal.Set(reflect.ValueOf(rawVal))
return nil
}
}
// Direct assignment for simple types
switch d := dest.(type) {
case *string:
switch v := rawVal.(type) {
case string:
*d = v
case []byte:
*d = string(v)
default:
b, _ := msgpack.Marshal(v)
*d = string(b)
}
return nil
case *[]byte:
switch v := rawVal.(type) {
case []byte:
*d = v
case string:
*d = []byte(v)
default:
*d, _ = msgpack.Marshal(v)
}
return nil
}
// Fallback to MsgPack unmarshaling
switch v := rawVal.(type) {
case []byte:
return msgpack.Unmarshal(v, dest)
case string:
return msgpack.Unmarshal([]byte(v), dest)
default:
b, err := msgpack.Marshal(v)
if err != nil {
return err
}
return msgpack.Unmarshal(b, dest)
}
}
// Get retrieves a key-value pair's serialized value from the local cache database.
// Returns an empty string and nil error if the key is not found or has expired.
func (f *Capacitor) Get(ctx context.Context, key string) (string, error) {
var start time.Time
if !f.disableMetrics {
start = time.Now()
}
res, err := f.getInternal(ctx, key)
if !f.disableMetrics {
f.metrics.GetLat.Record(time.Since(start))
}
return res, err
}
func (f *Capacitor) getInternal(ctx context.Context, key string) (string, error) {
val, err := f.store.get(key)
if err != nil {
return "", err
}
if val == nil {
return "", ErrKeyNotFound
}
res := ""
switch v := val.(type) {
case string:
res = v
case []byte:
res = string(v)
default:
b, _ := msgpack.Marshal(v)
res = string(b)
}
return res, nil
}
// Exists checks if a key exists in the cache and has not expired.
func (f *Capacitor) Exists(ctx context.Context, key string) (bool, error) {
var start time.Time
if !f.disableMetrics {
start = time.Now()
}
exists, err := f.store.exists(key)
if !f.disableMetrics {
f.metrics.GetLat.Record(time.Since(start))
}
return exists, err
}
// Delete removes a key-value pair from the local store and replicates the deletion tombstone to the cluster.
func (f *Capacitor) Delete(ctx context.Context, key string) error {
var start time.Time
if !f.disableMetrics {
start = time.Now()
}
ts := f.hlc.Now()
// 1. Local Write
if err := f.store.delete(key, ts); err != nil {
return err
}
// 2. Log Append
f.log.Append(LogEntry{
TS: ts,
BornAt: time.Now().UnixNano(),
Op: MsgDelete,
Key: key,
})
if !f.disableMetrics {
f.metrics.SetLat.Record(time.Since(start))
}
return nil
}
// IncrementBy increments a distributed PN-Counter key by the specified delta.
// It tracks counts per-node to construct CRDT conflict-free convergence.
func (f *Capacitor) IncrementBy(ctx context.Context, key string, delta int64) (int64, error) {
var start time.Time
if !f.disableMetrics {
start = time.Now()
}
val, err := f.store.increment(key, f.nodeID, float64(delta))
if err != nil {
return 0, err
}
nodeVal, _ := f.store.getNodeCount(key, f.nodeID)
f.log.Append(LogEntry{
TS: f.hlc.Now(),
BornAt: time.Now().UnixNano(),
Op: MsgIncr,
Key: key,
Delta: nodeVal,
NodeID: f.nodeID,
})
if !f.disableMetrics {
f.metrics.IncrLat.Record(time.Since(start))
}
return int64(val), nil
}
// GetMetrics returns a snapshot summary of all built-in metrics (latencies, counts).
func (f *Capacitor) GetMetrics() []Summary {
summaries := f.metrics.GetSummary()
// Append Log Overflows
summaries = append(summaries, Summary{
Metric: "DeltaLog Overflows",
Count: int64(atomic.LoadUint64(&f.log.Overflows)),
})
// Append Clock Smashes
f.hlc.mu.Lock()
clockSmashes := f.hlc.ClockSmashes
f.hlc.mu.Unlock()
summaries = append(summaries, Summary{
Metric: "Clock Smash Events",
Count: int64(clockSmashes),
})
// Append GC Runs and Tombstones Evicted
summaries = append(summaries, Summary{
Metric: "GC Runs",
Count: int64(atomic.LoadUint64(&f.store.gcRuns)),
})
summaries = append(summaries, Summary{
Metric: "Tombstones Evicted",
Count: int64(atomic.LoadUint64(&f.store.tombstonesEvicted)),
})
return summaries
}
// GossipAddr returns the actual local address and port bound by the gossip layer.
func (f *Capacitor) GossipAddr() string {
if f.ml == nil {
return ""
}
return fmt.Sprintf("127.0.0.1:%d", f.ml.LocalNode().Port)
}
// Increment increments a distributed PN-Counter key by 1.
func (f *Capacitor) Increment(ctx context.Context, key string) (int64, error) {
return f.IncrementBy(ctx, key, 1)
}
// GetCount retrieves the converged aggregate sum of a distributed counter across all nodes.
func (f *Capacitor) GetCount(ctx context.Context, key string) (int64, error) {
val, err := f.store.getAggregateCount(key)
return int64(val), err
}
// IncrementParallel performs concurrent increment calls for multiple counter keys.
func (f *Capacitor) IncrementParallel(ctx context.Context, keys []string) (map[string]int64, error) {
if len(keys) == 0 {
return make(map[string]int64), nil
}
if len(keys) == 1 {
val, err := f.Increment(ctx, keys[0])
if err != nil {
return nil, err
}
return map[string]int64{keys[0]: val}, nil
}
res := make(map[string]int64, len(keys))
var mu sync.Mutex
var wg sync.WaitGroup
var firstErr error
var errOnce sync.Once
for _, k := range keys {
wg.Add(1)
go func(key string) {
defer wg.Done()
val, err := f.Increment(ctx, key)
if err != nil {
errOnce.Do(func() { firstErr = err })
return
}
mu.Lock()
res[key] = val
mu.Unlock()
}(k)
}
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
return res, nil
}
// IncrementMetric records a floating-point update to a distributed aggregate metric
// (tracking both hit frequency and aggregated sums).
func (f *Capacitor) IncrementMetric(ctx context.Context, key string, delta float64) (Metric, error) {
m, err := f.store.incrementMetric(key, f.nodeID, delta)
if err != nil {
return Metric{}, err
}
f.log.Append(LogEntry{
TS: f.hlc.Now(),
Op: MsgMetric,
Key: key,
Delta: delta,
NodeID: f.nodeID,
})
return m, nil
}
// GetMetric retrieves the aggregated Metric details (count, sum, average) for the specified key.
func (f *Capacitor) GetMetric(ctx context.Context, key string) (Metric, error) {
return f.store.getAggregateMetric(key)
}
// IncrementMetricParallel updates multiple aggregate metrics concurrently.
func (f *Capacitor) IncrementMetricParallel(ctx context.Context, keys map[string]float64) (map[string]Metric, error) {
if len(keys) == 0 {
return make(map[string]Metric), nil
}
if len(keys) == 1 {
for k, d := range keys {
m, err := f.IncrementMetric(ctx, k, d)
if err != nil {
return nil, err
}
return map[string]Metric{k: m}, nil
}
}
res := make(map[string]Metric, len(keys))
var mu sync.Mutex
var wg sync.WaitGroup
var firstErr error
var errOnce sync.Once
for k, d := range keys {
wg.Add(1)
go func(key string, delta float64) {
defer wg.Done()
m, err := f.IncrementMetric(ctx, key, delta)
if err != nil {
errOnce.Do(func() { firstErr = err })
return
}
mu.Lock()
res[key] = m
mu.Unlock()
}(k, d)
}
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
return res, nil
}
// IncrementSlidingWindow appends an event timestamp for rate limiting or hit tracking,
// and returns the count of active occurrences within the rolling window duration.
func (f *Capacitor) IncrementSlidingWindow(ctx context.Context, key string, window time.Duration) (int64, error) {
ts := f.hlc.Now()
count, err := f.store.incrementSlidingWindow(key, ts.Physical, window)
if err != nil {
return 0, err