subscription.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package event
  17. import (
  18. "context"
  19. "sync"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common/mclock"
  22. )
  23. // Subscription represents a stream of events. The carrier of the events is typically a
  24. // channel, but isn't part of the interface.
  25. //
  26. // Subscriptions can fail while established. Failures are reported through an error
  27. // channel. It receives a value if there is an issue with the subscription (e.g. the
  28. // network connection delivering the events has been closed). Only one value will ever be
  29. // sent.
  30. //
  31. // The error channel is closed when the subscription ends successfully (i.e. when the
  32. // source of events is closed). It is also closed when Unsubscribe is called.
  33. //
  34. // The Unsubscribe method cancels the sending of events. You must call Unsubscribe in all
  35. // cases to ensure that resources related to the subscription are released. It can be
  36. // called any number of times.
  37. type Subscription interface {
  38. Err() <-chan error // returns the error channel
  39. Unsubscribe() // cancels sending of events, closing the error channel
  40. }
  41. // NewSubscription runs a producer function as a subscription in a new goroutine. The
  42. // channel given to the producer is closed when Unsubscribe is called. If fn returns an
  43. // error, it is sent on the subscription's error channel.
  44. func NewSubscription(producer func(<-chan struct{}) error) Subscription {
  45. s := &funcSub{unsub: make(chan struct{}), err: make(chan error, 1)}
  46. go func() {
  47. defer close(s.err)
  48. err := producer(s.unsub)
  49. s.mu.Lock()
  50. defer s.mu.Unlock()
  51. if !s.unsubscribed {
  52. if err != nil {
  53. s.err <- err
  54. }
  55. s.unsubscribed = true
  56. }
  57. }()
  58. return s
  59. }
  60. type funcSub struct {
  61. unsub chan struct{}
  62. err chan error
  63. mu sync.Mutex
  64. unsubscribed bool
  65. }
  66. func (s *funcSub) Unsubscribe() {
  67. s.mu.Lock()
  68. if s.unsubscribed {
  69. s.mu.Unlock()
  70. return
  71. }
  72. s.unsubscribed = true
  73. close(s.unsub)
  74. s.mu.Unlock()
  75. // Wait for producer shutdown.
  76. <-s.err
  77. }
  78. func (s *funcSub) Err() <-chan error {
  79. return s.err
  80. }
  81. // Resubscribe calls fn repeatedly to keep a subscription established. When the
  82. // subscription is established, Resubscribe waits for it to fail and calls fn again. This
  83. // process repeats until Unsubscribe is called or the active subscription ends
  84. // successfully.
  85. //
  86. // Resubscribe applies backoff between calls to fn. The time between calls is adapted
  87. // based on the error rate, but will never exceed backoffMax.
  88. func Resubscribe(backoffMax time.Duration, fn ResubscribeFunc) Subscription {
  89. return ResubscribeErr(backoffMax, func(ctx context.Context, _ error) (Subscription, error) {
  90. return fn(ctx)
  91. })
  92. }
  93. // A ResubscribeFunc attempts to establish a subscription.
  94. type ResubscribeFunc func(context.Context) (Subscription, error)
  95. // ResubscribeErr calls fn repeatedly to keep a subscription established. When the
  96. // subscription is established, ResubscribeErr waits for it to fail and calls fn again. This
  97. // process repeats until Unsubscribe is called or the active subscription ends
  98. // successfully.
  99. //
  100. // The difference between Resubscribe and ResubscribeErr is that with ResubscribeErr,
  101. // the error of the failing subscription is available to the callback for logging
  102. // purposes.
  103. //
  104. // ResubscribeErr applies backoff between calls to fn. The time between calls is adapted
  105. // based on the error rate, but will never exceed backoffMax.
  106. func ResubscribeErr(backoffMax time.Duration, fn ResubscribeErrFunc) Subscription {
  107. s := &resubscribeSub{
  108. waitTime: backoffMax / 10,
  109. backoffMax: backoffMax,
  110. fn: fn,
  111. err: make(chan error),
  112. unsub: make(chan struct{}),
  113. }
  114. go s.loop()
  115. return s
  116. }
  117. // A ResubscribeErrFunc attempts to establish a subscription.
  118. // For every call but the first, the second argument to this function is
  119. // the error that occurred with the previous subscription.
  120. type ResubscribeErrFunc func(context.Context, error) (Subscription, error)
  121. type resubscribeSub struct {
  122. fn ResubscribeErrFunc
  123. err chan error
  124. unsub chan struct{}
  125. unsubOnce sync.Once
  126. lastTry mclock.AbsTime
  127. lastSubErr error
  128. waitTime, backoffMax time.Duration
  129. }
  130. func (s *resubscribeSub) Unsubscribe() {
  131. s.unsubOnce.Do(func() {
  132. s.unsub <- struct{}{}
  133. <-s.err
  134. })
  135. }
  136. func (s *resubscribeSub) Err() <-chan error {
  137. return s.err
  138. }
  139. func (s *resubscribeSub) loop() {
  140. defer close(s.err)
  141. var done bool
  142. for !done {
  143. sub := s.subscribe()
  144. if sub == nil {
  145. break
  146. }
  147. done = s.waitForError(sub)
  148. sub.Unsubscribe()
  149. }
  150. }
  151. func (s *resubscribeSub) subscribe() Subscription {
  152. subscribed := make(chan error)
  153. var sub Subscription
  154. for {
  155. s.lastTry = mclock.Now()
  156. ctx, cancel := context.WithCancel(context.Background())
  157. go func() {
  158. rsub, err := s.fn(ctx, s.lastSubErr)
  159. sub = rsub
  160. subscribed <- err
  161. }()
  162. select {
  163. case err := <-subscribed:
  164. cancel()
  165. if err == nil {
  166. if sub == nil {
  167. panic("event: ResubscribeFunc returned nil subscription and no error")
  168. }
  169. return sub
  170. }
  171. // Subscribing failed, wait before launching the next try.
  172. if s.backoffWait() {
  173. return nil // unsubscribed during wait
  174. }
  175. case <-s.unsub:
  176. cancel()
  177. <-subscribed // avoid leaking the s.fn goroutine.
  178. return nil
  179. }
  180. }
  181. }
  182. func (s *resubscribeSub) waitForError(sub Subscription) bool {
  183. defer sub.Unsubscribe()
  184. select {
  185. case err := <-sub.Err():
  186. s.lastSubErr = err
  187. return err == nil
  188. case <-s.unsub:
  189. return true
  190. }
  191. }
  192. func (s *resubscribeSub) backoffWait() bool {
  193. if time.Duration(mclock.Now()-s.lastTry) > s.backoffMax {
  194. s.waitTime = s.backoffMax / 10
  195. } else {
  196. s.waitTime *= 2
  197. if s.waitTime > s.backoffMax {
  198. s.waitTime = s.backoffMax
  199. }
  200. }
  201. t := time.NewTimer(s.waitTime)
  202. defer t.Stop()
  203. select {
  204. case <-t.C:
  205. return false
  206. case <-s.unsub:
  207. return true
  208. }
  209. }
  210. // SubscriptionScope provides a facility to unsubscribe multiple subscriptions at once.
  211. //
  212. // For code that handle more than one subscription, a scope can be used to conveniently
  213. // unsubscribe all of them with a single call. The example demonstrates a typical use in a
  214. // larger program.
  215. //
  216. // The zero value is ready to use.
  217. type SubscriptionScope struct {
  218. mu sync.Mutex
  219. subs map[*scopeSub]struct{}
  220. closed bool
  221. }
  222. type scopeSub struct {
  223. sc *SubscriptionScope
  224. s Subscription
  225. }
  226. // Track starts tracking a subscription. If the scope is closed, Track returns nil. The
  227. // returned subscription is a wrapper. Unsubscribing the wrapper removes it from the
  228. // scope.
  229. func (sc *SubscriptionScope) Track(s Subscription) Subscription {
  230. sc.mu.Lock()
  231. defer sc.mu.Unlock()
  232. if sc.closed {
  233. return nil
  234. }
  235. if sc.subs == nil {
  236. sc.subs = make(map[*scopeSub]struct{})
  237. }
  238. ss := &scopeSub{sc, s}
  239. sc.subs[ss] = struct{}{}
  240. return ss
  241. }
  242. // Close calls Unsubscribe on all tracked subscriptions and prevents further additions to
  243. // the tracked set. Calls to Track after Close return nil.
  244. func (sc *SubscriptionScope) Close() {
  245. sc.mu.Lock()
  246. defer sc.mu.Unlock()
  247. if sc.closed {
  248. return
  249. }
  250. sc.closed = true
  251. for s := range sc.subs {
  252. s.s.Unsubscribe()
  253. }
  254. sc.subs = nil
  255. }
  256. // Count returns the number of tracked subscriptions.
  257. // It is meant to be used for debugging.
  258. func (sc *SubscriptionScope) Count() int {
  259. sc.mu.Lock()
  260. defer sc.mu.Unlock()
  261. return len(sc.subs)
  262. }
  263. func (s *scopeSub) Unsubscribe() {
  264. s.s.Unsubscribe()
  265. s.sc.mu.Lock()
  266. defer s.sc.mu.Unlock()
  267. delete(s.sc.subs, s)
  268. }
  269. func (s *scopeSub) Err() <-chan error {
  270. return s.s.Err()
  271. }