notification.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 rpc
  17. import (
  18. "errors"
  19. "sync"
  20. "time"
  21. "github.com/ethereum/go-ethereum/logger"
  22. "github.com/ethereum/go-ethereum/logger/glog"
  23. "golang.org/x/net/context"
  24. )
  25. var (
  26. // ErrNotificationsUnsupported is returned when the connection doesn't support notifications
  27. ErrNotificationsUnsupported = errors.New("notifications not supported")
  28. // ErrNotificationNotFound is returned when the notification for the given id is not found
  29. ErrNotificationNotFound = errors.New("notification not found")
  30. // errNotifierStopped is returned when the notifier is stopped (e.g. codec is closed)
  31. errNotifierStopped = errors.New("unable to send notification")
  32. // errNotificationQueueFull is returns when there are too many notifications in the queue
  33. errNotificationQueueFull = errors.New("too many pending notifications")
  34. )
  35. // unsubSignal is a signal that the subscription is unsubscribed. It is used to flush buffered
  36. // notifications that might be pending in the internal queue.
  37. var unsubSignal = new(struct{})
  38. // UnsubscribeCallback defines a callback that is called when a subcription ends.
  39. // It receives the subscription id as argument.
  40. type UnsubscribeCallback func(id string)
  41. // notification is a helper object that holds event data for a subscription
  42. type notification struct {
  43. sub *bufferedSubscription // subscription id
  44. data interface{} // event data
  45. }
  46. // A Notifier type describes the interface for objects that can send create subscriptions
  47. type Notifier interface {
  48. // Create a new subscription. The given callback is called when this subscription
  49. // is cancelled (e.g. client send an unsubscribe, connection closed).
  50. NewSubscription(UnsubscribeCallback) (Subscription, error)
  51. // Cancel subscription
  52. Unsubscribe(id string) error
  53. }
  54. type notifierKey struct{}
  55. // NotifierFromContext returns the Notifier value stored in ctx, if any.
  56. func NotifierFromContext(ctx context.Context) (Notifier, bool) {
  57. n, ok := ctx.Value(notifierKey{}).(Notifier)
  58. return n, ok
  59. }
  60. // Subscription defines the interface for objects that can notify subscribers
  61. type Subscription interface {
  62. // Inform client of an event
  63. Notify(data interface{}) error
  64. // Unique identifier
  65. ID() string
  66. // Cancel subscription
  67. Cancel() error
  68. }
  69. // bufferedSubscription is a subscription that uses a bufferedNotifier to send
  70. // notifications to subscribers.
  71. type bufferedSubscription struct {
  72. id string
  73. unsubOnce sync.Once // call unsub method once
  74. unsub UnsubscribeCallback // called on Unsubscribed
  75. notifier *bufferedNotifier // forward notifications to
  76. pending chan interface{} // closed when active
  77. flushed chan interface{} // closed when all buffered notifications are send
  78. lastNotification time.Time // last time a notification was send
  79. }
  80. // ID returns the subscription identifier that the client uses to refer to this instance.
  81. func (s *bufferedSubscription) ID() string {
  82. return s.id
  83. }
  84. // Cancel informs the notifier that this subscription is cancelled by the API
  85. func (s *bufferedSubscription) Cancel() error {
  86. return s.notifier.Unsubscribe(s.id)
  87. }
  88. // Notify the subscriber of a particular event.
  89. func (s *bufferedSubscription) Notify(data interface{}) error {
  90. return s.notifier.send(s.id, data)
  91. }
  92. // bufferedNotifier is a notifier that queues notifications in an internal queue and
  93. // send them as fast as possible to the client from this queue. It will stop if the
  94. // queue grows past a given size.
  95. type bufferedNotifier struct {
  96. codec ServerCodec // underlying connection
  97. mu sync.Mutex // guard internal state
  98. subscriptions map[string]*bufferedSubscription // keep track of subscriptions associated with codec
  99. queueSize int // max number of items in queue
  100. queue chan *notification // notification queue
  101. stopped bool // indication if this notifier is ordered to stop
  102. }
  103. // newBufferedNotifier returns a notifier that queues notifications in an internal queue
  104. // from which notifications are send as fast as possible to the client. If the queue size
  105. // limit is reached (client is unable to keep up) it will stop and closes the codec.
  106. func newBufferedNotifier(codec ServerCodec, size int) *bufferedNotifier {
  107. notifier := &bufferedNotifier{
  108. codec: codec,
  109. subscriptions: make(map[string]*bufferedSubscription),
  110. queue: make(chan *notification, size),
  111. queueSize: size,
  112. }
  113. go notifier.run()
  114. return notifier
  115. }
  116. // NewSubscription creates a new subscription that forwards events to this instance internal
  117. // queue. The given callback is called when the subscription is unsubscribed/cancelled.
  118. func (n *bufferedNotifier) NewSubscription(callback UnsubscribeCallback) (Subscription, error) {
  119. id, err := newSubscriptionID()
  120. if err != nil {
  121. return nil, err
  122. }
  123. n.mu.Lock()
  124. defer n.mu.Unlock()
  125. if n.stopped {
  126. return nil, errNotifierStopped
  127. }
  128. sub := &bufferedSubscription{
  129. id: id,
  130. unsub: callback,
  131. notifier: n,
  132. pending: make(chan interface{}),
  133. flushed: make(chan interface{}),
  134. lastNotification: time.Now(),
  135. }
  136. n.subscriptions[id] = sub
  137. return sub, nil
  138. }
  139. // Remove the given subscription. If subscription is not found notificationNotFoundErr is returned.
  140. func (n *bufferedNotifier) Unsubscribe(subid string) error {
  141. n.mu.Lock()
  142. sub, found := n.subscriptions[subid]
  143. n.mu.Unlock()
  144. if found {
  145. // send the unsubscribe signal, this will cause the notifier not to accept new events
  146. // for this subscription and will close the flushed channel after the last (buffered)
  147. // notification was send to the client.
  148. if err := n.send(subid, unsubSignal); err != nil {
  149. return err
  150. }
  151. // wait for confirmation that all (buffered) events are send for this subscription.
  152. // this ensures that the unsubscribe method response is not send before all buffered
  153. // events for this subscription are send.
  154. <-sub.flushed
  155. return nil
  156. }
  157. return ErrNotificationNotFound
  158. }
  159. // Send enques the given data for the subscription with public ID on the internal queue. t returns
  160. // an error when the notifier is stopped or the queue is full. If data is the unsubscribe signal it
  161. // will remove the subscription with the given id from the subscription collection.
  162. func (n *bufferedNotifier) send(id string, data interface{}) error {
  163. n.mu.Lock()
  164. defer n.mu.Unlock()
  165. if n.stopped {
  166. return errNotifierStopped
  167. }
  168. var (
  169. subscription *bufferedSubscription
  170. found bool
  171. )
  172. // check if subscription is associated with this connection, it might be cancelled
  173. // (subscribe/connection closed)
  174. if subscription, found = n.subscriptions[id]; !found {
  175. glog.V(logger.Error).Infof("received notification for unknown subscription %s\n", id)
  176. return ErrNotificationNotFound
  177. }
  178. // received the unsubscribe signal. Add it to the queue to make sure any pending notifications
  179. // for this subscription are send. When the run loop receives this singal it will signal that
  180. // all pending subscriptions are flushed and that the confirmation of the unsubscribe can be
  181. // send to the user. Remove the subscriptions to make sure new notifications are not accepted.
  182. if data == unsubSignal {
  183. delete(n.subscriptions, id)
  184. if subscription.unsub != nil {
  185. subscription.unsubOnce.Do(func() { subscription.unsub(id) })
  186. }
  187. }
  188. subscription.lastNotification = time.Now()
  189. if len(n.queue) >= n.queueSize {
  190. glog.V(logger.Warn).Infoln("too many buffered notifications -> close connection")
  191. n.codec.Close()
  192. return errNotificationQueueFull
  193. }
  194. n.queue <- &notification{subscription, data}
  195. return nil
  196. }
  197. // run reads notifications from the internal queue and sends them to the client. In case of an
  198. // error, or when the codec is closed it will cancel all active subscriptions and returns.
  199. func (n *bufferedNotifier) run() {
  200. defer func() {
  201. n.mu.Lock()
  202. defer n.mu.Unlock()
  203. n.stopped = true
  204. close(n.queue)
  205. // on exit call unsubscribe callback
  206. for id, sub := range n.subscriptions {
  207. if sub.unsub != nil {
  208. sub.unsubOnce.Do(func() { sub.unsub(id) })
  209. }
  210. close(sub.flushed)
  211. delete(n.subscriptions, id)
  212. }
  213. }()
  214. for {
  215. select {
  216. case notification := <-n.queue:
  217. // It can happen that an event is raised before the RPC server was able to send the sub
  218. // id to the client. Therefore subscriptions are marked as pending until the sub id was
  219. // send. The RPC server will activate the subscription by closing the pending chan.
  220. <-notification.sub.pending
  221. if notification.data == unsubSignal {
  222. // unsubSignal is the last accepted message for this subscription. Raise the signal
  223. // that all buffered notifications are sent by closing the flushed channel. This
  224. // indicates that the response for the unsubscribe can be send to the client.
  225. close(notification.sub.flushed)
  226. } else {
  227. msg := n.codec.CreateNotification(notification.sub.id, notification.data)
  228. if err := n.codec.Write(msg); err != nil {
  229. n.codec.Close()
  230. // unable to send notification to client, unsubscribe all subscriptions
  231. glog.V(logger.Warn).Infof("unable to send notification - %v\n", err)
  232. return
  233. }
  234. }
  235. case <-n.codec.Closed(): // connection was closed
  236. glog.V(logger.Debug).Infoln("codec closed, stop subscriptions")
  237. return
  238. }
  239. }
  240. }
  241. // Marks the subscription as active. This will causes the notifications for this subscription to be
  242. // forwarded to the client.
  243. func (n *bufferedNotifier) activate(subid string) {
  244. n.mu.Lock()
  245. defer n.mu.Unlock()
  246. if sub, found := n.subscriptions[subid]; found {
  247. close(sub.pending)
  248. }
  249. }