Skip to content

Commit

Permalink
optimize(lb): rebalance when weights updated
Browse files Browse the repository at this point in the history
  • Loading branch information
jizhuozhi committed Jul 5, 2024
1 parent 573dc2b commit 89a4d18
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
19 changes: 13 additions & 6 deletions pkg/discovery/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,20 @@ func DefaultDiff(cacheKey string, prev, next Result) (Change, bool) {
},
}

prevMap := make(map[string]struct{}, len(prev.Instances))
prevMap := make(map[string]Instance, len(prev.Instances))
for _, ins := range prev.Instances {
prevMap[ins.Address().String()] = struct{}{}
prevMap[ins.Address().String()] = ins
}

nextMap := make(map[string]struct{}, len(next.Instances))
nextMap := make(map[string]Instance, len(next.Instances))
for _, ins := range next.Instances {
addr := ins.Address().String()
nextMap[addr] = struct{}{}
if _, found := prevMap[addr]; !found {
nextMap[addr] = ins
// FIXME(jizhuozhi): tags should also be used to determine whether the instance has updated
if prevIns, found := prevMap[addr]; !found {
ch.Added = append(ch.Added, ins)
} else if prevIns.Weight() != ins.Weight() {
ch.Updated = append(ch.Updated, ins)
}
}

Expand All @@ -98,7 +101,7 @@ func DefaultDiff(cacheKey string, prev, next Result) (Change, bool) {
ch.Removed = append(ch.Removed, ins)
}
}
return ch, len(ch.Added)+len(ch.Removed) != 0
return ch, len(ch.Added)+len(ch.Updated)+len(ch.Removed) != 0
}

type instance struct {
Expand All @@ -120,6 +123,10 @@ func (i *instance) Tag(key string) (value string, exist bool) {
return
}

func (i *instance) Tags() map[string]string {
return i.tags
}

// NewInstance creates a Instance using the given network, address and tags
func NewInstance(network, address string, weight int, tags map[string]string) Instance {
return &instance{
Expand Down
5 changes: 3 additions & 2 deletions pkg/discovery/discovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,18 @@ func TestDefaultDiff(t *testing.T) {
Instances: []Instance{
NewInstance("tcp", "1", 10, nil),
NewInstance("tcp", "2", 10, nil),
NewInstance("tcp", "3", 10, nil),
NewInstance("tcp", "3", 20, nil),
NewInstance("tcp", "5", 10, nil),
},
}}, Change{
Result: Result{Instances: []Instance{
NewInstance("tcp", "1", 10, nil),
NewInstance("tcp", "2", 10, nil),
NewInstance("tcp", "3", 10, nil),
NewInstance("tcp", "3", 20, nil),
NewInstance("tcp", "5", 10, nil),
}, CacheKey: "1", Cacheable: true},
Added: []Instance{NewInstance("tcp", "5", 10, nil)},
Updated: []Instance{NewInstance("tcp", "3", 20, nil)},
Removed: []Instance{NewInstance("tcp", "4", 10, nil)},
}, true},
}
Expand Down

0 comments on commit 89a4d18

Please sign in to comment.