Skip to content

Commit

Permalink
fix: implement comparable interface for ir.Infra to avoid multiple re…
Browse files Browse the repository at this point in the history
…conciling (#2395)
  • Loading branch information
cnvergence authored Jan 5, 2024
1 parent 8760e31 commit 4daa348
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
20 changes: 20 additions & 0 deletions internal/ir/infra.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
package ir

import (
"cmp"
"errors"
"fmt"
"reflect"

"golang.org/x/exp/slices"
utilerrors "k8s.io/apimachinery/pkg/util/errors"

"github.com/envoyproxy/gateway/api/v1alpha1"
Expand Down Expand Up @@ -229,3 +232,20 @@ func (p *ProxyInfra) ObjectName() string {
}
return "envoy-" + p.Name
}

// Equal implements the Comparable interface used by watchable.DeepEqual to skip unnecessary updates.
func (p *ProxyInfra) Equal(y *ProxyInfra) bool {
// Deep copy to avoid modifying the original ordering.
p = p.DeepCopy()
p.sort()
y = y.DeepCopy()
y.sort()
return reflect.DeepEqual(p, y)
}

// sort ensures the listeners are in a consistent order.
func (p *ProxyInfra) sort() {
slices.SortFunc(p.Listeners, func(l1, l2 *ProxyListener) int {
return cmp.Compare(l1.Name, l2.Name)
})
}
33 changes: 33 additions & 0 deletions internal/ir/infra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package ir
import (
"testing"

"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -211,3 +212,35 @@ func TestObjectName(t *testing.T) {
})
}
}

func TestEqualInfra(t *testing.T) {
tests := []struct {
desc string
a *ProxyInfra
b *ProxyInfra
equal bool
}{
{
desc: "out of order proxy listeners are equal",
a: &ProxyInfra{
Listeners: []*ProxyListener{
{Name: "listener-1"},
{Name: "listener-2"},
},
},
b: &ProxyInfra{
Listeners: []*ProxyListener{
{Name: "listener-2"},
{Name: "listener-1"},
},
},
equal: true,
},
}

for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
require.Equal(t, tc.equal, cmp.Equal(tc.a, tc.b))
})
}
}

0 comments on commit 4daa348

Please sign in to comment.