watcher_single.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "github.com/coreos/etcd/clientv3"
  17. "golang.org/x/net/context"
  18. )
  19. type watcherSingle struct {
  20. // ch delievers events received from the etcd server
  21. ch clientv3.WatchChan
  22. // cancel is used to cancel the underlying etcd server watcher
  23. // It should also close the ch.
  24. cancel context.CancelFunc
  25. // sws is the stream this watcherSingle attached to
  26. sws *serverWatchStream
  27. w watcher
  28. rev int64 // current revision
  29. lastSeenRev int64
  30. donec chan struct{}
  31. }
  32. func newWatcherSingle(wch clientv3.WatchChan, c context.CancelFunc, w watcher, sws *serverWatchStream) *watcherSingle {
  33. return &watcherSingle{
  34. sws: sws,
  35. ch: wch,
  36. cancel: c,
  37. w: w,
  38. donec: make(chan struct{}),
  39. }
  40. }
  41. func (ws watcherSingle) run() {
  42. defer close(ws.donec)
  43. for wr := range ws.ch {
  44. ws.rev = wr.Header.Revision
  45. ws.w.send(wr)
  46. ws.lastSeenRev = wr.Events[len(wr.Events)-1].Kv.ModRevision
  47. if ws.sws.maybeCoalesceWatcher(ws) {
  48. return
  49. }
  50. }
  51. }
  52. // canPromote returns true if a watcherSingle can promote itself to a watchergroup
  53. // when it already caught up with the current revision.
  54. func (ws watcherSingle) canPromote() bool {
  55. return ws.rev == ws.lastSeenRev
  56. }
  57. func (ws watcherSingle) stop() {
  58. ws.cancel()
  59. <-ws.donec
  60. }