subscription.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. "container/list"
  19. "context"
  20. crand "crypto/rand"
  21. "encoding/binary"
  22. "encoding/hex"
  23. "encoding/json"
  24. "errors"
  25. "math/rand"
  26. "reflect"
  27. "strings"
  28. "sync"
  29. "time"
  30. )
  31. var (
  32. // ErrNotificationsUnsupported is returned when the connection doesn't support notifications
  33. ErrNotificationsUnsupported = errors.New("notifications not supported")
  34. // ErrNotificationNotFound is returned when the notification for the given id is not found
  35. ErrSubscriptionNotFound = errors.New("subscription not found")
  36. )
  37. var globalGen = randomIDGenerator()
  38. // ID defines a pseudo random number that is used to identify RPC subscriptions.
  39. type ID string
  40. // NewID returns a new, random ID.
  41. func NewID() ID {
  42. return globalGen()
  43. }
  44. // randomIDGenerator returns a function generates a random IDs.
  45. func randomIDGenerator() func() ID {
  46. var buf = make([]byte, 8)
  47. var seed int64
  48. if _, err := crand.Read(buf); err == nil {
  49. seed = int64(binary.BigEndian.Uint64(buf))
  50. } else {
  51. seed = int64(time.Now().Nanosecond())
  52. }
  53. var (
  54. mu sync.Mutex
  55. rng = rand.New(rand.NewSource(seed))
  56. )
  57. return func() ID {
  58. mu.Lock()
  59. defer mu.Unlock()
  60. id := make([]byte, 16)
  61. rng.Read(id)
  62. return encodeID(id)
  63. }
  64. }
  65. func encodeID(b []byte) ID {
  66. id := hex.EncodeToString(b)
  67. id = strings.TrimLeft(id, "0")
  68. if id == "" {
  69. id = "0" // ID's are RPC quantities, no leading zero's and 0 is 0x0.
  70. }
  71. return ID("0x" + id)
  72. }
  73. type notifierKey struct{}
  74. // NotifierFromContext returns the Notifier value stored in ctx, if any.
  75. func NotifierFromContext(ctx context.Context) (*Notifier, bool) {
  76. n, ok := ctx.Value(notifierKey{}).(*Notifier)
  77. return n, ok
  78. }
  79. // Notifier is tied to a RPC connection that supports subscriptions.
  80. // Server callbacks use the notifier to send notifications.
  81. type Notifier struct {
  82. h *handler
  83. namespace string
  84. mu sync.Mutex
  85. sub *Subscription
  86. buffer []json.RawMessage
  87. callReturned bool
  88. activated bool
  89. }
  90. // CreateSubscription returns a new subscription that is coupled to the
  91. // RPC connection. By default subscriptions are inactive and notifications
  92. // are dropped until the subscription is marked as active. This is done
  93. // by the RPC server after the subscription ID is send to the client.
  94. func (n *Notifier) CreateSubscription() *Subscription {
  95. n.mu.Lock()
  96. defer n.mu.Unlock()
  97. if n.sub != nil {
  98. panic("can't create multiple subscriptions with Notifier")
  99. } else if n.callReturned {
  100. panic("can't create subscription after subscribe call has returned")
  101. }
  102. n.sub = &Subscription{ID: n.h.idgen(), namespace: n.namespace, err: make(chan error, 1)}
  103. return n.sub
  104. }
  105. // Notify sends a notification to the client with the given data as payload.
  106. // If an error occurs the RPC connection is closed and the error is returned.
  107. func (n *Notifier) Notify(id ID, data interface{}) error {
  108. enc, err := json.Marshal(data)
  109. if err != nil {
  110. return err
  111. }
  112. n.mu.Lock()
  113. defer n.mu.Unlock()
  114. if n.sub == nil {
  115. panic("can't Notify before subscription is created")
  116. } else if n.sub.ID != id {
  117. panic("Notify with wrong ID")
  118. }
  119. if n.activated {
  120. return n.send(n.sub, enc)
  121. }
  122. n.buffer = append(n.buffer, enc)
  123. return nil
  124. }
  125. // Closed returns a channel that is closed when the RPC connection is closed.
  126. // Deprecated: use subscription error channel
  127. func (n *Notifier) Closed() <-chan interface{} {
  128. return n.h.conn.closed()
  129. }
  130. // takeSubscription returns the subscription (if one has been created). No subscription can
  131. // be created after this call.
  132. func (n *Notifier) takeSubscription() *Subscription {
  133. n.mu.Lock()
  134. defer n.mu.Unlock()
  135. n.callReturned = true
  136. return n.sub
  137. }
  138. // activate is called after the subscription ID was sent to client. Notifications are
  139. // buffered before activation. This prevents notifications being sent to the client before
  140. // the subscription ID is sent to the client.
  141. func (n *Notifier) activate() error {
  142. n.mu.Lock()
  143. defer n.mu.Unlock()
  144. for _, data := range n.buffer {
  145. if err := n.send(n.sub, data); err != nil {
  146. return err
  147. }
  148. }
  149. n.activated = true
  150. return nil
  151. }
  152. func (n *Notifier) send(sub *Subscription, data json.RawMessage) error {
  153. params, _ := json.Marshal(&subscriptionResult{ID: string(sub.ID), Result: data})
  154. ctx := context.Background()
  155. return n.h.conn.writeJSON(ctx, &jsonrpcMessage{
  156. Version: vsn,
  157. Method: n.namespace + notificationMethodSuffix,
  158. Params: params,
  159. })
  160. }
  161. // A Subscription is created by a notifier and tied to that notifier. The client can use
  162. // this subscription to wait for an unsubscribe request for the client, see Err().
  163. type Subscription struct {
  164. ID ID
  165. namespace string
  166. err chan error // closed on unsubscribe
  167. }
  168. // Err returns a channel that is closed when the client send an unsubscribe request.
  169. func (s *Subscription) Err() <-chan error {
  170. return s.err
  171. }
  172. // MarshalJSON marshals a subscription as its ID.
  173. func (s *Subscription) MarshalJSON() ([]byte, error) {
  174. return json.Marshal(s.ID)
  175. }
  176. // ClientSubscription is a subscription established through the Client's Subscribe or
  177. // EthSubscribe methods.
  178. type ClientSubscription struct {
  179. client *Client
  180. etype reflect.Type
  181. channel reflect.Value
  182. namespace string
  183. subid string
  184. in chan json.RawMessage
  185. quitOnce sync.Once // ensures quit is closed once
  186. quit chan struct{} // quit is closed when the subscription exits
  187. errOnce sync.Once // ensures err is closed once
  188. err chan error
  189. }
  190. func newClientSubscription(c *Client, namespace string, channel reflect.Value) *ClientSubscription {
  191. sub := &ClientSubscription{
  192. client: c,
  193. namespace: namespace,
  194. etype: channel.Type().Elem(),
  195. channel: channel,
  196. quit: make(chan struct{}),
  197. err: make(chan error, 1),
  198. in: make(chan json.RawMessage),
  199. }
  200. return sub
  201. }
  202. // Err returns the subscription error channel. The intended use of Err is to schedule
  203. // resubscription when the client connection is closed unexpectedly.
  204. //
  205. // The error channel receives a value when the subscription has ended due
  206. // to an error. The received error is nil if Close has been called
  207. // on the underlying client and no other error has occurred.
  208. //
  209. // The error channel is closed when Unsubscribe is called on the subscription.
  210. func (sub *ClientSubscription) Err() <-chan error {
  211. return sub.err
  212. }
  213. // Unsubscribe unsubscribes the notification and closes the error channel.
  214. // It can safely be called more than once.
  215. func (sub *ClientSubscription) Unsubscribe() {
  216. sub.quitWithError(true, nil)
  217. sub.errOnce.Do(func() { close(sub.err) })
  218. }
  219. func (sub *ClientSubscription) quitWithError(unsubscribeServer bool, err error) {
  220. sub.quitOnce.Do(func() {
  221. // The dispatch loop won't be able to execute the unsubscribe call
  222. // if it is blocked on deliver. Close sub.quit first because it
  223. // unblocks deliver.
  224. close(sub.quit)
  225. if unsubscribeServer {
  226. sub.requestUnsubscribe()
  227. }
  228. if err != nil {
  229. if err == ErrClientQuit {
  230. err = nil // Adhere to subscription semantics.
  231. }
  232. sub.err <- err
  233. }
  234. })
  235. }
  236. func (sub *ClientSubscription) deliver(result json.RawMessage) (ok bool) {
  237. select {
  238. case sub.in <- result:
  239. return true
  240. case <-sub.quit:
  241. return false
  242. }
  243. }
  244. func (sub *ClientSubscription) start() {
  245. sub.quitWithError(sub.forward())
  246. }
  247. func (sub *ClientSubscription) forward() (unsubscribeServer bool, err error) {
  248. cases := []reflect.SelectCase{
  249. {Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
  250. {Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)},
  251. {Dir: reflect.SelectSend, Chan: sub.channel},
  252. }
  253. buffer := list.New()
  254. defer buffer.Init()
  255. for {
  256. var chosen int
  257. var recv reflect.Value
  258. if buffer.Len() == 0 {
  259. // Idle, omit send case.
  260. chosen, recv, _ = reflect.Select(cases[:2])
  261. } else {
  262. // Non-empty buffer, send the first queued item.
  263. cases[2].Send = reflect.ValueOf(buffer.Front().Value)
  264. chosen, recv, _ = reflect.Select(cases)
  265. }
  266. switch chosen {
  267. case 0: // <-sub.quit
  268. return false, nil
  269. case 1: // <-sub.in
  270. val, err := sub.unmarshal(recv.Interface().(json.RawMessage))
  271. if err != nil {
  272. return true, err
  273. }
  274. if buffer.Len() == maxClientSubscriptionBuffer {
  275. return true, ErrSubscriptionQueueOverflow
  276. }
  277. buffer.PushBack(val)
  278. case 2: // sub.channel<-
  279. cases[2].Send = reflect.Value{} // Don't hold onto the value.
  280. buffer.Remove(buffer.Front())
  281. }
  282. }
  283. }
  284. func (sub *ClientSubscription) unmarshal(result json.RawMessage) (interface{}, error) {
  285. val := reflect.New(sub.etype)
  286. err := json.Unmarshal(result, val.Interface())
  287. return val.Elem().Interface(), err
  288. }
  289. func (sub *ClientSubscription) requestUnsubscribe() error {
  290. var result interface{}
  291. return sub.client.Call(&result, sub.namespace+unsubscribeMethodSuffix, sub.subid)
  292. }