istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/kube/krt/util.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package krt 16 17 import ( 18 "istio.io/istio/pkg/slices" 19 ) 20 21 // BatchedEventFilter allows an event handler to have alternative event suppression mechanics to filter out unnecessary events. 22 // For instance, I can make a transformation from `object => object.name` to only trigger events for changes to the name; 23 // the output will be compared (using standard equality checking), and only changes will trigger the handler. 24 // Note this is in addition to the normal event mechanics, so this can only filter things further. 25 func BatchedEventFilter[I, O any](cf func(a I) O, handler func(events []Event[I], initialSync bool)) func(o []Event[I], initialSync bool) { 26 return func(events []Event[I], initialSync bool) { 27 ev := slices.FilterInPlace(events, func(e Event[I]) bool { 28 if e.Old != nil && e.New != nil { 29 if equal(cf(*e.Old), cf(*e.New)) { 30 // Equal under conversion, so we can skip 31 return false 32 } 33 } 34 return true 35 }) 36 if len(ev) == 0 { 37 return 38 } 39 handler(ev, initialSync) 40 } 41 }