watch.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "context"
  17. "go.etcd.io/etcd/clientv3"
  18. "go.etcd.io/etcd/mvcc/mvccpb"
  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. ctx, cancel := context.WithCancel(context.Background())
  23. defer cancel()
  24. wc := c.Watch(ctx, key, clientv3.WithRev(rev))
  25. if wc == nil {
  26. return nil, ErrNoWatcher
  27. }
  28. return waitEvents(wc, evs), nil
  29. }
  30. func WaitPrefixEvents(c *clientv3.Client, prefix string, rev int64, evs []mvccpb.Event_EventType) (*clientv3.Event, error) {
  31. ctx, cancel := context.WithCancel(context.Background())
  32. defer cancel()
  33. wc := c.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithRev(rev))
  34. if wc == nil {
  35. return nil, ErrNoWatcher
  36. }
  37. return waitEvents(wc, evs), nil
  38. }
  39. func waitEvents(wc clientv3.WatchChan, evs []mvccpb.Event_EventType) *clientv3.Event {
  40. i := 0
  41. for wresp := range wc {
  42. for _, ev := range wresp.Events {
  43. if ev.Type == evs[i] {
  44. i++
  45. if i == len(evs) {
  46. return ev
  47. }
  48. }
  49. }
  50. }
  51. return nil
  52. }