feat: build wahrwelt A/D toolkit

This commit is contained in:
TakuyaYagam1 committed 2026-10-14 11:30:41 +03:00
1 parent 303438d206
commit 653924d8c6
564 files changed
+36310 -49998

No files matched your search

@@ -0,0 +1,51 @@
package rendezvous
import (
"hash"
"sync"
"github.com/sirupsen/logrus"
"github.com/spaolacci/murmur3"
)
type Rendezvous struct {
hcache map[string]uint64
mu sync.RWMutex
h hash.Hash64
}
func New() *Rendezvous {
return &Rendezvous{
hcache: make(map[string]uint64),
h: murmur3.New64WithSeed(1337),
}
}
func (r *Rendezvous) checkCache(key string) (uint64, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
raw, ok := r.hcache[key]
return raw, ok
}
func (r *Rendezvous) calcHash(key string) uint64 {
r.mu.Lock()
defer r.mu.Unlock()
r.h.Reset()
if _, err := r.h.Write([]byte(key)); err != nil {
logrus.Fatalf("Не удалось вычислить хэш: %v", err)
}
rawVal := r.h.Sum64()
r.hcache[key] = rawVal
return rawVal
}
func (r *Rendezvous) Calculate(node string, weight int, value string) float64 {
key := combineKey(node, value)
if raw, ok := r.checkCache(key); ok {
return weightHash(raw, weight)
}
raw := r.calcHash(key)
return weightHash(raw, weight)
}
@@ -0,0 +1,38 @@
package rendezvous
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestRendezvous_Calculate(t *testing.T) {
tests := []struct {
name string
nodeID string
nodeWeight int
value string
}{
{
"simple_test",
"kek",
1,
"lol",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := New()
hash := r.Calculate(tt.nodeID, tt.nodeWeight, tt.value)
if hash == 0 {
t.Error("Zero hash returned")
}
k := combineKey(tt.nodeID, tt.value)
rhash, ok := r.checkCache(k)
require.True(t, ok)
needHash := weightHash(rhash, tt.nodeWeight)
require.Equal(t, needHash, hash)
})
}
}
+14
View File
@@ -0,0 +1,14 @@
package rendezvous
import "math"
const maxUInt64 = float64(^uint64(0))
func combineKey(nodeID, value string) string {
return nodeID + ":" + value
}
func weightHash(hash uint64, weight int) float64 {
scale := 1.0 / -math.Log(float64(hash)/maxUInt64)
return scale * float64(weight)
}