wait.go 2.1 KB

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