resource_watcher.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. package testutils
  19. import "google.golang.org/grpc/xds/internal/xdsclient/xdsresource"
  20. // TestResourceWatcher implements the xdsresource.ResourceWatcher interface,
  21. // used to receive updates on watches registered with the xDS client, when using
  22. // the resource-type agnostic WatchResource API.
  23. //
  24. // Tests can the channels provided by this tyep to get access to updates and
  25. // errors sent by the xDS client.
  26. type TestResourceWatcher struct {
  27. // UpdateCh is the channel on which xDS client updates are delivered.
  28. UpdateCh chan *xdsresource.ResourceData
  29. // ErrorCh is the channel on which errors from the xDS client are delivered.
  30. ErrorCh chan error
  31. // ResourceDoesNotExistCh is the channel used to indicate calls to OnResourceDoesNotExist
  32. ResourceDoesNotExistCh chan struct{}
  33. }
  34. // OnUpdate is invoked by the xDS client to report the latest update on the resource
  35. // being watched.
  36. func (w *TestResourceWatcher) OnUpdate(data xdsresource.ResourceData) {
  37. select {
  38. case <-w.UpdateCh:
  39. default:
  40. }
  41. w.UpdateCh <- &data
  42. }
  43. // OnError is invoked by the xDS client to report the latest error.
  44. func (w *TestResourceWatcher) OnError(err error) {
  45. select {
  46. case <-w.ErrorCh:
  47. default:
  48. }
  49. w.ErrorCh <- err
  50. }
  51. // OnResourceDoesNotExist is used by the xDS client to report that the resource
  52. // being watched no longer exists.
  53. func (w *TestResourceWatcher) OnResourceDoesNotExist() {
  54. select {
  55. case <-w.ResourceDoesNotExistCh:
  56. default:
  57. }
  58. w.ResourceDoesNotExistCh <- struct{}{}
  59. }
  60. // NewTestResourceWatcher returns a TestResourceWatcher to watch for resources
  61. // via the xDS client.
  62. func NewTestResourceWatcher() *TestResourceWatcher {
  63. return &TestResourceWatcher{
  64. UpdateCh: make(chan *xdsresource.ResourceData, 1),
  65. ErrorCh: make(chan error, 1),
  66. ResourceDoesNotExistCh: make(chan struct{}, 1),
  67. }
  68. }