Skip to content

Commit 172b3a0

Browse files
committed
dist: add methods and test
1 parent 4de06e9 commit 172b3a0

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

dist.go

+28
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,34 @@ func (d *Distributed) VNodeIndex(cell h3.H3Index) int {
303303
return int(hashKey % d.vnodes)
304304
}
305305

306+
// EachVNode iterate each vnode, calling fn for each vnode.
307+
func (d *Distributed) EachVNode(fn func(vnode uint64, addr string) bool) {
308+
for i := uint64(0); i < d.vnodes; i++ {
309+
addr, ok := d.Addr(i)
310+
if !ok {
311+
continue
312+
}
313+
if !fn(i, addr) {
314+
break
315+
}
316+
}
317+
}
318+
319+
// Addr returns the addr of the node by vnode id.
320+
func (d *Distributed) Addr(vnode uint64) (addr string, ok bool) {
321+
hashKey := uint2hash(vnode)
322+
idx := int(hashKey % d.vnodes)
323+
d.mu.RLock()
324+
node, found := d.index[idx]
325+
d.mu.RUnlock()
326+
if !found {
327+
return
328+
}
329+
addr = node.addr
330+
ok = true
331+
return
332+
}
333+
306334
// EachCell iterate each distributed cell, calling fn for each cell.
307335
func (d *Distributed) EachCell(iter func(c Cell)) {
308336
d.mu.RLock()

dist_test.go

+60
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,66 @@ func TestDistributed_NeighborsFromLatLon(t *testing.T) {
288288
}
289289
}
290290

291+
func TestDistributed_EachVNode(t *testing.T) {
292+
h3dist, err := New(Level3)
293+
if err != nil {
294+
t.Fatal(err)
295+
}
296+
297+
hosts := []string{
298+
"127.0.0.1",
299+
"127.0.0.2",
300+
"127.0.0.3",
301+
}
302+
for _, host := range hosts {
303+
_ = h3dist.Add(host)
304+
}
305+
stats := make(map[string]int)
306+
307+
h3dist.EachVNode(func(id uint64, addr string) bool {
308+
stats[addr]++
309+
return true
310+
})
311+
for _, host := range hosts {
312+
counter := stats[host]
313+
if counter == 0 {
314+
t.Fatalf("have %d, want > 0", counter)
315+
}
316+
}
317+
}
318+
319+
func TestDistributed_Addr(t *testing.T) {
320+
h3dist, err := New(Level3)
321+
if err != nil {
322+
t.Fatal(err)
323+
}
324+
325+
hosts := []string{
326+
"127.0.0.1",
327+
"127.0.0.2",
328+
"127.0.0.3",
329+
}
330+
for _, host := range hosts {
331+
_ = h3dist.Add(host)
332+
}
333+
334+
stats := make(map[string]int)
335+
for i := uint64(0); i < h3dist.VNodes(); i++ {
336+
addr, ok := h3dist.Addr(i)
337+
if !ok {
338+
continue
339+
}
340+
stats[addr]++
341+
}
342+
343+
for _, host := range hosts {
344+
counter := stats[host]
345+
if counter == 0 {
346+
t.Fatalf("have %d, want > 0", counter)
347+
}
348+
}
349+
}
350+
291351
func TestDistributed_WhereIsMyParent(t *testing.T) {
292352
h3dist, err := New(Level3)
293353
if err != nil {

0 commit comments

Comments
 (0)