watcher.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "time"
  17. "github.com/coreos/etcd/clientv3"
  18. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  19. "github.com/coreos/etcd/mvcc"
  20. "github.com/coreos/etcd/mvcc/mvccpb"
  21. )
  22. type watchRange struct {
  23. key, end string
  24. }
  25. type watcher struct {
  26. id int64
  27. wr watchRange
  28. rev int64
  29. filters []mvcc.FilterFunc
  30. progress bool
  31. ch chan<- *pb.WatchResponse
  32. }
  33. func (w *watcher) send(wr clientv3.WatchResponse) {
  34. if wr.IsProgressNotify() && !w.progress {
  35. return
  36. }
  37. events := make([]*mvccpb.Event, 0, len(wr.Events))
  38. var lastRev int64
  39. for i := range wr.Events {
  40. ev := (*mvccpb.Event)(wr.Events[i])
  41. if ev.Kv.ModRevision <= w.rev {
  42. continue
  43. } else {
  44. // We cannot update w.rev here.
  45. // txn can have multiple events with the same rev.
  46. // If we update w.rev here, we would skip some events in the same txn.
  47. lastRev = ev.Kv.ModRevision
  48. }
  49. filtered := false
  50. if len(w.filters) != 0 {
  51. for _, filter := range w.filters {
  52. if filter(*ev) {
  53. filtered = true
  54. break
  55. }
  56. }
  57. }
  58. if !filtered {
  59. events = append(events, ev)
  60. }
  61. }
  62. if lastRev > w.rev {
  63. w.rev = lastRev
  64. }
  65. // all events are filtered out?
  66. if !wr.IsProgressNotify() && !wr.Created && len(events) == 0 {
  67. return
  68. }
  69. pbwr := &pb.WatchResponse{
  70. Header: &wr.Header,
  71. Created: wr.Created,
  72. WatchId: w.id,
  73. Events: events,
  74. }
  75. select {
  76. case w.ch <- pbwr:
  77. case <-time.After(50 * time.Millisecond):
  78. // close the watch chan will notify the stream sender.
  79. // the stream will gc all its watchers.
  80. close(w.ch)
  81. }
  82. }