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.

257 lines
7.4 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
6 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
6 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
6 years ago
8 years ago
8 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
6 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. // WriteRPCResponseHTTPError marshals res as JSON and writes it to w.
  84. //
  85. // Panics if it can't Marshal res or write to w.
  86. func WriteRPCResponseHTTPError(
  87. w http.ResponseWriter,
  88. httpCode int,
  89. res types.RPCResponse,
  90. ) {
  91. jsonBytes, err := json.MarshalIndent(res, "", " ")
  92. if err != nil {
  93. panic(err)
  94. }
  95. w.Header().Set("Content-Type", "application/json")
  96. w.WriteHeader(httpCode)
  97. if _, err := w.Write(jsonBytes); err != nil {
  98. panic(err)
  99. }
  100. }
  101. // WriteRPCResponseHTTP marshals res as JSON and writes it to w.
  102. //
  103. // Panics if it can't Marshal res or write to w.
  104. func WriteRPCResponseHTTP(w http.ResponseWriter, res ...types.RPCResponse) {
  105. var v interface{}
  106. if len(res) == 1 {
  107. v = res[0]
  108. } else {
  109. v = res
  110. }
  111. jsonBytes, err := json.MarshalIndent(v, "", " ")
  112. if err != nil {
  113. panic(err)
  114. }
  115. w.Header().Set("Content-Type", "application/json")
  116. w.WriteHeader(200)
  117. if _, err := w.Write(jsonBytes); err != nil {
  118. panic(err)
  119. }
  120. }
  121. //-----------------------------------------------------------------------------
  122. // RecoverAndLogHandler wraps an HTTP handler, adding error logging.
  123. // If the inner function panics, the outer function recovers, logs, sends an
  124. // HTTP 500 error response.
  125. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  126. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  127. // Wrap the ResponseWriter to remember the status
  128. rww := &responseWriterWrapper{-1, w}
  129. begin := time.Now()
  130. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  131. defer func() {
  132. // Handle any panics in the panic handler below. Does not use the logger, since we want
  133. // to avoid any further panics. However, we try to return a 500, since it otherwise
  134. // defaults to 200 and there is no other way to terminate the connection. If that
  135. // should panic for whatever reason then the Go HTTP server will handle it and
  136. // terminate the connection - panicing is the de-facto and only way to get the Go HTTP
  137. // server to terminate the request and close the connection/stream:
  138. // https://github.com/golang/go/issues/17790#issuecomment-258481416
  139. if e := recover(); e != nil {
  140. fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack()))
  141. w.WriteHeader(500)
  142. }
  143. }()
  144. defer func() {
  145. // Send a 500 error if a panic happens during a handler.
  146. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  147. // at least to my localhost.
  148. if e := recover(); e != nil {
  149. // If RPCResponse
  150. if res, ok := e.(types.RPCResponse); ok {
  151. WriteRPCResponseHTTP(rww, res)
  152. } else {
  153. // Panics can contain anything, attempt to normalize it as an error.
  154. var err error
  155. switch e := e.(type) {
  156. case error:
  157. err = e
  158. case string:
  159. err = errors.New(e)
  160. case fmt.Stringer:
  161. err = errors.New(e.String())
  162. default:
  163. }
  164. logger.Error(
  165. "Panic in RPC HTTP handler", "err", e, "stack",
  166. string(debug.Stack()),
  167. )
  168. WriteRPCResponseHTTPError(
  169. rww,
  170. http.StatusInternalServerError,
  171. types.RPCInternalError(types.JSONRPCIntID(-1), err),
  172. )
  173. }
  174. }
  175. // Finally, log.
  176. durationMS := time.Since(begin).Nanoseconds() / 1000000
  177. if rww.Status == -1 {
  178. rww.Status = 200
  179. }
  180. logger.Info("Served RPC HTTP response",
  181. "method", r.Method, "url", r.URL,
  182. "status", rww.Status, "duration", durationMS,
  183. "remoteAddr", r.RemoteAddr,
  184. )
  185. }()
  186. handler.ServeHTTP(rww, r)
  187. })
  188. }
  189. // Remember the status for logging
  190. type responseWriterWrapper struct {
  191. Status int
  192. http.ResponseWriter
  193. }
  194. func (w *responseWriterWrapper) WriteHeader(status int) {
  195. w.Status = status
  196. w.ResponseWriter.WriteHeader(status)
  197. }
  198. // implements http.Hijacker
  199. func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  200. return w.ResponseWriter.(http.Hijacker).Hijack()
  201. }
  202. type maxBytesHandler struct {
  203. h http.Handler
  204. n int64
  205. }
  206. func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  207. r.Body = http.MaxBytesReader(w, r.Body, h.n)
  208. h.h.ServeHTTP(w, r)
  209. }
  210. // Listen starts a new net.Listener on the given address.
  211. // It returns an error if the address is invalid or the call to Listen() fails.
  212. func Listen(addr string, config *Config) (listener net.Listener, err error) {
  213. parts := strings.SplitN(addr, "://", 2)
  214. if len(parts) != 2 {
  215. return nil, fmt.Errorf(
  216. "invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
  217. addr,
  218. )
  219. }
  220. proto, addr := parts[0], parts[1]
  221. listener, err = net.Listen(proto, addr)
  222. if err != nil {
  223. return nil, fmt.Errorf("failed to listen on %v: %v", addr, err)
  224. }
  225. if config.MaxOpenConnections > 0 {
  226. listener = netutil.LimitListener(listener, config.MaxOpenConnections)
  227. }
  228. return listener, nil
  229. }