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 // ErrorCh is the channel on which errors from the xDS client are delivered. 33 ErrorCh chan error 34 // ResourceDoesNotExistCh is the channel used to indicate calls to OnResourceDoesNotExist 35 ResourceDoesNotExistCh chan struct{} 36 } 37 38 // OnUpdate is invoked by the xDS client to report the latest update on the resource 39 // being watched. 40 func (w *TestResourceWatcher) OnUpdate(data xdsresource.ResourceData) { 41 select { 42 case <-w.UpdateCh: 43 default: 44 } 45 w.UpdateCh <- &data 46 } 47 48 // OnError is invoked by the xDS client to report the latest error. 49 func (w *TestResourceWatcher) OnError(err error) { 50 select { 51 case <-w.ErrorCh: 52 default: 53 } 54 w.ErrorCh <- err 55 } 56 57 // OnResourceDoesNotExist is used by the xDS client to report that the resource 58 // being watched no longer exists. 59 func (w *TestResourceWatcher) OnResourceDoesNotExist() { 60 select { 61 case <-w.ResourceDoesNotExistCh: 62 default: 63 } 64 w.ResourceDoesNotExistCh <- struct{}{} 65 } 66 67 // NewTestResourceWatcher returns a TestResourceWatcher to watch for resources 68 // via the xDS client. 69 func NewTestResourceWatcher() *TestResourceWatcher { 70 return &TestResourceWatcher{ 71 UpdateCh: make(chan *xdsresource.ResourceData, 1), 72 ErrorCh: make(chan error, 1), 73 ResourceDoesNotExistCh: make(chan struct{}, 1), 74 } 75 } 76