watcher.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // Copyright 2015 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 mvcc
  15. import (
  16. "bytes"
  17. "errors"
  18. "sync"
  19. "github.com/coreos/etcd/mvcc/mvccpb"
  20. )
  21. var (
  22. ErrWatcherNotExist = errors.New("mvcc: watcher does not exist")
  23. )
  24. type WatchID int64
  25. // FilterFunc returns true if the given event should be filtered out.
  26. type FilterFunc func(e mvccpb.Event) bool
  27. type WatchStream interface {
  28. // Watch creates a watcher. The watcher watches the events happening or
  29. // happened on the given key or range [key, end) from the given startRev.
  30. //
  31. // The whole event history can be watched unless compacted.
  32. // If `startRev` <=0, watch observes events after currentRev.
  33. //
  34. // The returned `id` is the ID of this watcher. It appears as WatchID
  35. // in events that are sent to the created watcher through stream channel.
  36. //
  37. Watch(key, end []byte, startRev int64, fcs ...FilterFunc) WatchID
  38. // Chan returns a chan. All watch response will be sent to the returned chan.
  39. Chan() <-chan WatchResponse
  40. // RequestProgress requests the progress of the watcher with given ID. The response
  41. // will only be sent if the watcher is currently synced.
  42. // The responses will be sent through the WatchRespone Chan attached
  43. // with this stream to ensure correct ordering.
  44. // The responses contains no events. The revision in the response is the progress
  45. // of the watchers since the watcher is currently synced.
  46. RequestProgress(id WatchID)
  47. // Cancel cancels a watcher by giving its ID. If watcher does not exist, an error will be
  48. // returned.
  49. Cancel(id WatchID) error
  50. // Close closes Chan and release all related resources.
  51. Close()
  52. // Rev returns the current revision of the KV the stream watches on.
  53. Rev() int64
  54. }
  55. type WatchResponse struct {
  56. // WatchID is the WatchID of the watcher this response sent to.
  57. WatchID WatchID
  58. // Events contains all the events that needs to send.
  59. Events []mvccpb.Event
  60. // Revision is the revision of the KV when the watchResponse is created.
  61. // For a normal response, the revision should be the same as the last
  62. // modified revision inside Events. For a delayed response to a unsynced
  63. // watcher, the revision is greater than the last modified revision
  64. // inside Events.
  65. Revision int64
  66. // CompactRevision is set when the watcher is cancelled due to compaction.
  67. CompactRevision int64
  68. }
  69. // watchStream contains a collection of watchers that share
  70. // one streaming chan to send out watched events and other control events.
  71. type watchStream struct {
  72. watchable watchable
  73. ch chan WatchResponse
  74. mu sync.Mutex // guards fields below it
  75. // nextID is the ID pre-allocated for next new watcher in this stream
  76. nextID WatchID
  77. closed bool
  78. cancels map[WatchID]cancelFunc
  79. watchers map[WatchID]*watcher
  80. }
  81. // Watch creates a new watcher in the stream and returns its WatchID.
  82. // TODO: return error if ws is closed?
  83. func (ws *watchStream) Watch(key, end []byte, startRev int64, fcs ...FilterFunc) WatchID {
  84. // prevent wrong range where key >= end lexicographically
  85. // watch request with 'WithFromKey' has empty-byte range end
  86. if len(end) != 0 && bytes.Compare(key, end) != -1 {
  87. return -1
  88. }
  89. ws.mu.Lock()
  90. defer ws.mu.Unlock()
  91. if ws.closed {
  92. return -1
  93. }
  94. id := ws.nextID
  95. ws.nextID++
  96. w, c := ws.watchable.watch(key, end, startRev, id, ws.ch, fcs...)
  97. ws.cancels[id] = c
  98. ws.watchers[id] = w
  99. return id
  100. }
  101. func (ws *watchStream) Chan() <-chan WatchResponse {
  102. return ws.ch
  103. }
  104. func (ws *watchStream) Cancel(id WatchID) error {
  105. ws.mu.Lock()
  106. cancel, ok := ws.cancels[id]
  107. w := ws.watchers[id]
  108. ok = ok && !ws.closed
  109. ws.mu.Unlock()
  110. if !ok {
  111. return ErrWatcherNotExist
  112. }
  113. cancel()
  114. ws.mu.Lock()
  115. // The watch isn't removed until cancel so that if Close() is called,
  116. // it will wait for the cancel. Otherwise, Close() could close the
  117. // watch channel while the store is still posting events.
  118. if ww := ws.watchers[id]; ww == w {
  119. delete(ws.cancels, id)
  120. delete(ws.watchers, id)
  121. }
  122. ws.mu.Unlock()
  123. return nil
  124. }
  125. func (ws *watchStream) Close() {
  126. ws.mu.Lock()
  127. defer ws.mu.Unlock()
  128. for _, cancel := range ws.cancels {
  129. cancel()
  130. }
  131. ws.closed = true
  132. close(ws.ch)
  133. watchStreamGauge.Dec()
  134. }
  135. func (ws *watchStream) Rev() int64 {
  136. ws.mu.Lock()
  137. defer ws.mu.Unlock()
  138. return ws.watchable.rev()
  139. }
  140. func (ws *watchStream) RequestProgress(id WatchID) {
  141. ws.mu.Lock()
  142. w, ok := ws.watchers[id]
  143. ws.mu.Unlock()
  144. if !ok {
  145. return
  146. }
  147. ws.watchable.progress(w)
  148. }