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.

263 lines
7.6 KiB

rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
7 years ago
7 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
  1. // Commons for HTTP handling
  2. package server
  3. import (
  4. "bufio"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "os"
  11. "runtime/debug"
  12. "strings"
  13. "time"
  14. "golang.org/x/net/netutil"
  15. "github.com/tendermint/tendermint/libs/log"
  16. types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
  17. )
  18. // Config is a RPC server configuration.
  19. type Config struct {
  20. // see netutil.LimitListener
  21. MaxOpenConnections int
  22. // mirrors http.Server#ReadTimeout
  23. ReadTimeout time.Duration
  24. // mirrors http.Server#WriteTimeout
  25. WriteTimeout time.Duration
  26. // MaxBodyBytes controls the maximum number of bytes the
  27. // server will read parsing the request body.
  28. MaxBodyBytes int64
  29. // mirrors http.Server#MaxHeaderBytes
  30. MaxHeaderBytes int
  31. }
  32. // DefaultConfig returns a default configuration.
  33. func DefaultConfig() *Config {
  34. return &Config{
  35. MaxOpenConnections: 0, // unlimited
  36. ReadTimeout: 10 * time.Second,
  37. WriteTimeout: 10 * time.Second,
  38. MaxBodyBytes: int64(1000000), // 1MB
  39. MaxHeaderBytes: 1 << 20, // same as the net/http default
  40. }
  41. }
  42. // Serve creates a http.Server and calls Serve with the given listener. It
  43. // wraps handler with RecoverAndLogHandler and a handler, which limits the max
  44. // body size to config.MaxBodyBytes.
  45. //
  46. // NOTE: This function blocks - you may want to call it in a go-routine.
  47. func Serve(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
  48. logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s", listener.Addr()))
  49. s := &http.Server{
  50. Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger),
  51. ReadTimeout: config.ReadTimeout,
  52. WriteTimeout: config.WriteTimeout,
  53. MaxHeaderBytes: config.MaxHeaderBytes,
  54. }
  55. err := s.Serve(listener)
  56. logger.Info("RPC HTTP server stopped", "err", err)
  57. return err
  58. }
  59. // Serve creates a http.Server and calls ServeTLS with the given listener,
  60. // certFile and keyFile. It wraps handler with RecoverAndLogHandler and a
  61. // handler, which limits the max body size to config.MaxBodyBytes.
  62. //
  63. // NOTE: This function blocks - you may want to call it in a go-routine.
  64. func ServeTLS(
  65. listener net.Listener,
  66. handler http.Handler,
  67. certFile, keyFile string,
  68. logger log.Logger,
  69. config *Config,
  70. ) error {
  71. logger.Info(fmt.Sprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)",
  72. listener.Addr(), certFile, keyFile))
  73. s := &http.Server{
  74. Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger),
  75. ReadTimeout: config.ReadTimeout,
  76. WriteTimeout: config.WriteTimeout,
  77. MaxHeaderBytes: config.MaxHeaderBytes,
  78. }
  79. err := s.ServeTLS(listener, certFile, keyFile)
  80. logger.Error("RPC HTTPS server stopped", "err", err)
  81. return err
  82. }
  83. func WriteRPCResponseHTTPError(
  84. w http.ResponseWriter,
  85. httpCode int,
  86. res types.RPCResponse,
  87. ) {
  88. jsonBytes, err := json.MarshalIndent(res, "", " ")
  89. if err != nil {
  90. panic(err)
  91. }
  92. w.Header().Set("Content-Type", "application/json")
  93. w.WriteHeader(httpCode)
  94. if _, err := w.Write(jsonBytes); err != nil {
  95. panic(err)
  96. }
  97. }
  98. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  99. jsonBytes, err := json.MarshalIndent(res, "", " ")
  100. if err != nil {
  101. panic(err)
  102. }
  103. w.Header().Set("Content-Type", "application/json")
  104. w.WriteHeader(200)
  105. if _, err := w.Write(jsonBytes); err != nil {
  106. panic(err)
  107. }
  108. }
  109. // WriteRPCResponseArrayHTTP will do the same as WriteRPCResponseHTTP, except it
  110. // can write arrays of responses for batched request/response interactions via
  111. // the JSON RPC.
  112. func WriteRPCResponseArrayHTTP(w http.ResponseWriter, res []types.RPCResponse) {
  113. if len(res) == 1 {
  114. WriteRPCResponseHTTP(w, res[0])
  115. } else {
  116. jsonBytes, err := json.MarshalIndent(res, "", " ")
  117. if err != nil {
  118. panic(err)
  119. }
  120. w.Header().Set("Content-Type", "application/json")
  121. w.WriteHeader(200)
  122. if _, err := w.Write(jsonBytes); err != nil {
  123. panic(err)
  124. }
  125. }
  126. }
  127. //-----------------------------------------------------------------------------
  128. // RecoverAndLogHandler wraps an HTTP handler, adding error logging.
  129. // If the inner function panics, the outer function recovers, logs, sends an
  130. // HTTP 500 error response.
  131. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  132. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  133. // Wrap the ResponseWriter to remember the status
  134. rww := &responseWriterWrapper{-1, w}
  135. begin := time.Now()
  136. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  137. defer func() {
  138. // Handle any panics in the panic handler below. Does not use the logger, since we want
  139. // to avoid any further panics. However, we try to return a 500, since it otherwise
  140. // defaults to 200 and there is no other way to terminate the connection. If that
  141. // should panic for whatever reason then the Go HTTP server will handle it and
  142. // terminate the connection - panicing is the de-facto and only way to get the Go HTTP
  143. // server to terminate the request and close the connection/stream:
  144. // https://github.com/golang/go/issues/17790#issuecomment-258481416
  145. if e := recover(); e != nil {
  146. fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack()))
  147. w.WriteHeader(500)
  148. }
  149. }()
  150. defer func() {
  151. // Send a 500 error if a panic happens during a handler.
  152. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  153. // at least to my localhost.
  154. if e := recover(); e != nil {
  155. // If RPCResponse
  156. if res, ok := e.(types.RPCResponse); ok {
  157. WriteRPCResponseHTTP(rww, res)
  158. } else {
  159. // Panics can contain anything, attempt to normalize it as an error.
  160. var err error
  161. switch e := e.(type) {
  162. case error:
  163. err = e
  164. case string:
  165. err = errors.New(e)
  166. case fmt.Stringer:
  167. err = errors.New(e.String())
  168. default:
  169. }
  170. logger.Error(
  171. "Panic in RPC HTTP handler", "err", e, "stack",
  172. string(debug.Stack()),
  173. )
  174. WriteRPCResponseHTTPError(
  175. rww,
  176. http.StatusInternalServerError,
  177. types.RPCInternalError(types.JSONRPCIntID(-1), err),
  178. )
  179. }
  180. }
  181. // Finally, log.
  182. durationMS := time.Since(begin).Nanoseconds() / 1000000
  183. if rww.Status == -1 {
  184. rww.Status = 200
  185. }
  186. logger.Info("Served RPC HTTP response",
  187. "method", r.Method, "url", r.URL,
  188. "status", rww.Status, "duration", durationMS,
  189. "remoteAddr", r.RemoteAddr,
  190. )
  191. }()
  192. handler.ServeHTTP(rww, r)
  193. })
  194. }
  195. // Remember the status for logging
  196. type responseWriterWrapper struct {
  197. Status int
  198. http.ResponseWriter
  199. }
  200. func (w *responseWriterWrapper) WriteHeader(status int) {
  201. w.Status = status
  202. w.ResponseWriter.WriteHeader(status)
  203. }
  204. // implements http.Hijacker
  205. func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  206. return w.ResponseWriter.(http.Hijacker).Hijack()
  207. }
  208. type maxBytesHandler struct {
  209. h http.Handler
  210. n int64
  211. }
  212. func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  213. r.Body = http.MaxBytesReader(w, r.Body, h.n)
  214. h.h.ServeHTTP(w, r)
  215. }
  216. // Listen starts a new net.Listener on the given address.
  217. // It returns an error if the address is invalid or the call to Listen() fails.
  218. func Listen(addr string, config *Config) (listener net.Listener, err error) {
  219. parts := strings.SplitN(addr, "://", 2)
  220. if len(parts) != 2 {
  221. return nil, fmt.Errorf(
  222. "invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
  223. addr,
  224. )
  225. }
  226. proto, addr := parts[0], parts[1]
  227. listener, err = net.Listen(proto, addr)
  228. if err != nil {
  229. return nil, fmt.Errorf("failed to listen on %v: %v", addr, err)
  230. }
  231. if config.MaxOpenConnections > 0 {
  232. listener = netutil.LimitListener(listener, config.MaxOpenConnections)
  233. }
  234. return listener, nil
  235. }