watch.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 recipe
  15. import (
  16. "github.com/coreos/etcd/clientv3"
  17. "github.com/coreos/etcd/mvcc/mvccpb"
  18. "golang.org/x/net/context"
  19. )
  20. // WaitEvents waits on a key until it observes the given events and returns the final one.
  21. func WaitEvents(c *clientv3.Client, key string, rev int64, evs []mvccpb.Event_EventType) (*clientv3.Event, error) {
  22. wc := c.Watch(context.Background(), key, clientv3.WithRev(rev))
  23. if wc == nil {
  24. return nil, ErrNoWatcher
  25. }
  26. return waitEvents(wc, evs), nil
  27. }
  28. func WaitPrefixEvents(c *clientv3.Client, prefix string, rev int64, evs []mvccpb.Event_EventType) (*clientv3.Event, error) {
  29. wc := c.Watch(context.Background(), prefix, clientv3.WithPrefix(), clientv3.WithRev(rev))
  30. if wc == nil {
  31. return nil, ErrNoWatcher
  32. }
  33. return waitEvents(wc, evs), nil
  34. }
  35. func waitEvents(wc clientv3.WatchChan, evs []mvccpb.Event_EventType) *clientv3.Event {
  36. i := 0
  37. for wresp := range wc {
  38. for _, ev := range wresp.Events {
  39. if ev.Type == evs[i] {
  40. i++
  41. if i == len(evs) {
  42. return ev
  43. }
  44. }
  45. }
  46. }
  47. return nil
  48. }