You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

255 lines
6.2 KiB

  1. package http
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  9. tmjson "github.com/tendermint/tendermint/libs/json"
  10. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  11. "github.com/tendermint/tendermint/libs/service"
  12. rpcclient "github.com/tendermint/tendermint/rpc/client"
  13. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  14. jsonrpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
  15. )
  16. var errNotRunning = errors.New("client is not running. Use .Start() method to start")
  17. // WSOptions for the WS part of the HTTP client.
  18. type WSOptions struct {
  19. Path string // path (e.g. "/ws")
  20. jsonrpcclient.WSOptions // WSClient options
  21. }
  22. // DefaultWSOptions returns default WS options.
  23. // See jsonrpcclient.DefaultWSOptions.
  24. func DefaultWSOptions() WSOptions {
  25. return WSOptions{
  26. Path: "/websocket",
  27. WSOptions: jsonrpcclient.DefaultWSOptions(),
  28. }
  29. }
  30. // Validate performs a basic validation of WSOptions.
  31. func (wso WSOptions) Validate() error {
  32. if len(wso.Path) <= 1 {
  33. return errors.New("empty Path")
  34. }
  35. if wso.Path[0] != '/' {
  36. return errors.New("leading slash is missing in Path")
  37. }
  38. return nil
  39. }
  40. // wsEvents is a wrapper around WSClient, which implements EventsClient.
  41. type wsEvents struct {
  42. service.BaseService
  43. ws *jsonrpcclient.WSClient
  44. mtx tmsync.RWMutex
  45. subscriptions map[string]chan ctypes.ResultEvent // query -> chan
  46. }
  47. var _ rpcclient.EventsClient = (*wsEvents)(nil)
  48. func newWsEvents(remote string, wso WSOptions) (*wsEvents, error) {
  49. // validate options
  50. if err := wso.Validate(); err != nil {
  51. return nil, fmt.Errorf("invalid WSOptions: %w", err)
  52. }
  53. // remove the trailing / from the remote else the websocket endpoint
  54. // won't parse correctly
  55. if remote[len(remote)-1] == '/' {
  56. remote = remote[:len(remote)-1]
  57. }
  58. w := &wsEvents{
  59. subscriptions: make(map[string]chan ctypes.ResultEvent),
  60. }
  61. w.BaseService = *service.NewBaseService(nil, "wsEvents", w)
  62. var err error
  63. w.ws, err = jsonrpcclient.NewWSWithOptions(remote, wso.Path, wso.WSOptions)
  64. if err != nil {
  65. return nil, fmt.Errorf("can't create WS client: %w", err)
  66. }
  67. w.ws.OnReconnect(func() {
  68. // resubscribe immediately
  69. w.redoSubscriptionsAfter(0 * time.Second)
  70. })
  71. w.ws.SetLogger(w.Logger)
  72. return w, nil
  73. }
  74. // OnStart implements service.Service by starting WSClient and event loop.
  75. func (w *wsEvents) OnStart() error {
  76. if err := w.ws.Start(); err != nil {
  77. return err
  78. }
  79. go w.eventListener()
  80. return nil
  81. }
  82. // OnStop implements service.Service by stopping WSClient.
  83. func (w *wsEvents) OnStop() {
  84. if err := w.ws.Stop(); err != nil {
  85. w.Logger.Error("Can't stop ws client", "err", err)
  86. }
  87. }
  88. // Subscribe implements EventsClient by using WSClient to subscribe given
  89. // subscriber to query. By default, it returns a channel with cap=1. Error is
  90. // returned if it fails to subscribe.
  91. //
  92. // When reading from the channel, keep in mind there's a single events loop, so
  93. // if you don't read events for this subscription fast enough, other
  94. // subscriptions will slow down in effect.
  95. //
  96. // The channel is never closed to prevent clients from seeing an erroneous
  97. // event.
  98. //
  99. // It returns an error if wsEvents is not running.
  100. func (w *wsEvents) Subscribe(ctx context.Context, subscriber, query string,
  101. outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) {
  102. if !w.IsRunning() {
  103. return nil, errNotRunning
  104. }
  105. if err := w.ws.Subscribe(ctx, query); err != nil {
  106. return nil, err
  107. }
  108. outCap := 1
  109. if len(outCapacity) > 0 {
  110. outCap = outCapacity[0]
  111. }
  112. outc := make(chan ctypes.ResultEvent, outCap)
  113. w.mtx.Lock()
  114. // subscriber param is ignored because Tendermint will override it with
  115. // remote IP anyway.
  116. w.subscriptions[query] = outc
  117. w.mtx.Unlock()
  118. return outc, nil
  119. }
  120. // Unsubscribe implements EventsClient by using WSClient to unsubscribe given
  121. // subscriber from query.
  122. //
  123. // It returns an error if wsEvents is not running.
  124. func (w *wsEvents) Unsubscribe(ctx context.Context, subscriber, query string) error {
  125. if !w.IsRunning() {
  126. return errNotRunning
  127. }
  128. if err := w.ws.Unsubscribe(ctx, query); err != nil {
  129. return err
  130. }
  131. w.mtx.Lock()
  132. _, ok := w.subscriptions[query]
  133. if ok {
  134. delete(w.subscriptions, query)
  135. }
  136. w.mtx.Unlock()
  137. return nil
  138. }
  139. // UnsubscribeAll implements EventsClient by using WSClient to unsubscribe
  140. // given subscriber from all the queries.
  141. //
  142. // It returns an error if wsEvents is not running.
  143. func (w *wsEvents) UnsubscribeAll(ctx context.Context, subscriber string) error {
  144. if !w.IsRunning() {
  145. return errNotRunning
  146. }
  147. if err := w.ws.UnsubscribeAll(ctx); err != nil {
  148. return err
  149. }
  150. w.mtx.Lock()
  151. w.subscriptions = make(map[string]chan ctypes.ResultEvent)
  152. w.mtx.Unlock()
  153. return nil
  154. }
  155. // After being reconnected, it is necessary to redo subscription to server
  156. // otherwise no data will be automatically received.
  157. func (w *wsEvents) redoSubscriptionsAfter(d time.Duration) {
  158. time.Sleep(d)
  159. ctx := context.Background()
  160. w.mtx.Lock()
  161. defer w.mtx.Unlock()
  162. for q := range w.subscriptions {
  163. err := w.ws.Subscribe(ctx, q)
  164. if err != nil {
  165. w.Logger.Error("failed to resubscribe", "query", q, "err", err)
  166. delete(w.subscriptions, q)
  167. }
  168. }
  169. }
  170. func isErrAlreadySubscribed(err error) bool {
  171. return strings.Contains(err.Error(), tmpubsub.ErrAlreadySubscribed.Error())
  172. }
  173. func (w *wsEvents) eventListener() {
  174. for {
  175. select {
  176. case resp, ok := <-w.ws.ResponsesCh:
  177. if !ok {
  178. return
  179. }
  180. if resp.Error != nil {
  181. w.Logger.Error("WS error", "err", resp.Error.Error())
  182. // Error can be ErrAlreadySubscribed or max client (subscriptions per
  183. // client) reached or Tendermint exited.
  184. // We can ignore ErrAlreadySubscribed, but need to retry in other
  185. // cases.
  186. if !isErrAlreadySubscribed(resp.Error) {
  187. // Resubscribe after 1 second to give Tendermint time to restart (if
  188. // crashed).
  189. w.redoSubscriptionsAfter(1 * time.Second)
  190. }
  191. continue
  192. }
  193. result := new(ctypes.ResultEvent)
  194. err := tmjson.Unmarshal(resp.Result, result)
  195. if err != nil {
  196. w.Logger.Error("failed to unmarshal response", "err", err)
  197. continue
  198. }
  199. w.mtx.RLock()
  200. out, ok := w.subscriptions[result.Query]
  201. w.mtx.RUnlock()
  202. if ok {
  203. select {
  204. case out <- *result:
  205. case <-w.Quit():
  206. return
  207. }
  208. }
  209. case <-w.Quit():
  210. return
  211. }
  212. }
  213. }