wait.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2015 CoreOS, Inc.
  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 wait provides utility functions for polling, listening using Go
  15. // channel.
  16. package wait
  17. import (
  18. "sync"
  19. "github.com/coreos/etcd/pkg/testutil"
  20. )
  21. type Wait interface {
  22. Register(id uint64) <-chan interface{}
  23. Trigger(id uint64, x interface{})
  24. }
  25. type List struct {
  26. l sync.Mutex
  27. m map[uint64]chan interface{}
  28. }
  29. func New() *List {
  30. return &List{m: make(map[uint64]chan interface{})}
  31. }
  32. func (w *List) Register(id uint64) <-chan interface{} {
  33. w.l.Lock()
  34. defer w.l.Unlock()
  35. ch := w.m[id]
  36. if ch == nil {
  37. ch = make(chan interface{}, 1)
  38. w.m[id] = ch
  39. }
  40. return ch
  41. }
  42. func (w *List) Trigger(id uint64, x interface{}) {
  43. w.l.Lock()
  44. ch := w.m[id]
  45. delete(w.m, id)
  46. w.l.Unlock()
  47. if ch != nil {
  48. ch <- x
  49. close(ch)
  50. }
  51. }
  52. type WaitRecorder struct {
  53. Wait
  54. testutil.Recorder
  55. }
  56. type waitRecorder struct {
  57. testutil.RecorderBuffered
  58. }
  59. func NewRecorder() *WaitRecorder {
  60. wr := &waitRecorder{}
  61. return &WaitRecorder{Wait: wr, Recorder: wr}
  62. }
  63. func NewNop() Wait { return NewRecorder() }
  64. func (w *waitRecorder) Register(id uint64) <-chan interface{} {
  65. w.Record(testutil.Action{Name: "Register"})
  66. return nil
  67. }
  68. func (w *waitRecorder) Trigger(id uint64, x interface{}) {
  69. w.Record(testutil.Action{Name: "Trigger"})
  70. }
  71. type waitWithResponse struct {
  72. ch <-chan interface{}
  73. }
  74. func NewWithResponse(ch <-chan interface{}) Wait {
  75. return &waitWithResponse{ch: ch}
  76. }
  77. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  78. return w.ch
  79. }
  80. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}