google.golang.org/grpc@v1.74.2/xds/internal/testutils/resource_watcher.go (about) 1 /* 2 * 3 * Copyright 2023 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package testutils 20 21 import "google.golang.org/grpc/xds/internal/xdsclient/xdsresource" 22 23 // TestResourceWatcher implements the xdsresource.ResourceWatcher interface, 24 // used to receive updates on watches registered with the xDS client, when using 25 // the resource-type agnostic WatchResource API. 26 // 27 // Tests can use the channels provided by this type to get access to updates and 28 // errors sent by the xDS client. 29 type TestResourceWatcher struct { 30 // UpdateCh is the channel on which xDS client updates are delivered. 31 UpdateCh chan *xdsresource.ResourceData 32 // AmbientErrorCh is the channel on which ambient errors from the xDS 33 // client are delivered. 34 AmbientErrorCh chan error 35 // ResourceErrorCh is the channel on which resource errors from the xDS 36 // client are delivered. 37 ResourceErrorCh chan struct{} 38 } 39 40 // ResourceChanged is invoked by the xDS client to report the latest update. 41 func (w *TestResourceWatcher) ResourceChanged(data xdsresource.ResourceData, onDone func()) { 42 defer onDone() 43 select { 44 case <-w.UpdateCh: 45 default: 46 } 47 w.UpdateCh <- &data 48 49 } 50 51 // ResourceError is invoked by the xDS client to report the latest error to 52 // stop watching the resource. 53 func (w *TestResourceWatcher) ResourceError(err error, onDone func()) { 54 defer onDone() 55 select { 56 case <-w.ResourceErrorCh: 57 case <-w.AmbientErrorCh: 58 default: 59 } 60 w.AmbientErrorCh <- err 61 w.ResourceErrorCh <- struct{}{} 62 } 63 64 // AmbientError is invoked by the xDS client to report the latest ambient 65 // error. 66 func (w *TestResourceWatcher) AmbientError(err error, onDone func()) { 67 defer onDone() 68 select { 69 case <-w.AmbientErrorCh: 70 default: 71 } 72 w.AmbientErrorCh <- err 73 } 74 75 // NewTestResourceWatcher returns a TestResourceWatcher to watch for resources 76 // via the xDS client. 77 func NewTestResourceWatcher() *TestResourceWatcher { 78 return &TestResourceWatcher{ 79 UpdateCh: make(chan *xdsresource.ResourceData, 1), 80 AmbientErrorCh: make(chan error, 1), 81 ResourceErrorCh: make(chan struct{}, 1), 82 } 83 }