watch_ranges.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2016 The etcd 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. package grpcproxy
  15. import (
  16. "sync"
  17. )
  18. // watchRanges tracks all open watches for the proxy.
  19. type watchRanges struct {
  20. wp *watchProxy
  21. mu sync.Mutex
  22. bcasts map[watchRange]*watchBroadcasts
  23. }
  24. func newWatchRanges(wp *watchProxy) *watchRanges {
  25. return &watchRanges{
  26. wp: wp,
  27. bcasts: make(map[watchRange]*watchBroadcasts),
  28. }
  29. }
  30. func (wrs *watchRanges) add(w *watcher) {
  31. wrs.mu.Lock()
  32. defer wrs.mu.Unlock()
  33. if wbs := wrs.bcasts[w.wr]; wbs != nil {
  34. wbs.add(w)
  35. return
  36. }
  37. wbs := newWatchBroadcasts(wrs.wp)
  38. wrs.bcasts[w.wr] = wbs
  39. wbs.add(w)
  40. }
  41. func (wrs *watchRanges) delete(w *watcher) {
  42. wrs.mu.Lock()
  43. defer wrs.mu.Unlock()
  44. wbs, ok := wrs.bcasts[w.wr]
  45. if !ok {
  46. panic("deleting missing range")
  47. }
  48. if wbs.delete(w) == 0 {
  49. wbs.stop()
  50. delete(wrs.bcasts, w.wr)
  51. }
  52. }
  53. func (wrs *watchRanges) stop() {
  54. wrs.mu.Lock()
  55. defer wrs.mu.Unlock()
  56. for _, wb := range wrs.bcasts {
  57. wb.stop()
  58. }
  59. wrs.bcasts = nil
  60. }