sigs.k8s.io/kueue@v0.6.2/pkg/util/routine/error_channel.go (about) 1 /* 2 Copyright 2023 The Kubernetes Authors. 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 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 */ 13 14 package routine 15 16 import "context" 17 18 // Code from https://github.com/kubernetes/kubernetes/blob/master/pkg/scheduler/framework/parallelize/error_channel.go 19 20 // ErrorChannel supports non-blocking send and receive operation to capture error. 21 // A maximum of one error is kept in the channel and the rest of the errors sent 22 // are ignored, unless the existing error is received and the channel becomes empty 23 // again. 24 type ErrorChannel struct { 25 errCh chan error 26 } 27 28 // SendError sends an error without blocking the sender. 29 func (e *ErrorChannel) SendError(err error) { 30 select { 31 case e.errCh <- err: 32 default: 33 } 34 } 35 36 // SendErrorWithCancel sends an error without blocking the sender and calls 37 // cancel function. 38 func (e *ErrorChannel) SendErrorWithCancel(err error, cancel context.CancelFunc) { 39 e.SendError(err) 40 cancel() 41 } 42 43 // ReceiveError receives an error from channel without blocking on the receiver. 44 func (e *ErrorChannel) ReceiveError() error { 45 select { 46 case err := <-e.errCh: 47 return err 48 default: 49 return nil 50 } 51 } 52 53 // NewErrorChannel returns a new ErrorChannel. 54 func NewErrorChannel() *ErrorChannel { 55 return &ErrorChannel{ 56 errCh: make(chan error, 1), 57 } 58 }