watcher.go 2.0 KB

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