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.

231 lines
6.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
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 rpcserver
  3. import (
  4. "bufio"
  5. "encoding/json"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "runtime/debug"
  10. "strings"
  11. "time"
  12. "github.com/pkg/errors"
  13. "golang.org/x/net/netutil"
  14. "github.com/tendermint/tendermint/libs/log"
  15. types "github.com/tendermint/tendermint/rpc/lib/types"
  16. )
  17. // Config is a RPC server configuration.
  18. type Config struct {
  19. // see netutil.LimitListener
  20. MaxOpenConnections int
  21. // mirrors http.Server#ReadTimeout
  22. ReadTimeout time.Duration
  23. // mirrors http.Server#WriteTimeout
  24. WriteTimeout time.Duration
  25. }
  26. // DefaultConfig returns a default configuration.
  27. func DefaultConfig() *Config {
  28. return &Config{
  29. MaxOpenConnections: 0, // unlimited
  30. ReadTimeout: 10 * time.Second,
  31. WriteTimeout: 10 * time.Second,
  32. }
  33. }
  34. const (
  35. // maxBodyBytes controls the maximum number of bytes the
  36. // server will read parsing the request body.
  37. maxBodyBytes = int64(1000000) // 1MB
  38. // same as the net/http default
  39. maxHeaderBytes = 1 << 20
  40. )
  41. // StartHTTPServer takes a listener and starts an HTTP server with the given handler.
  42. // It wraps handler with RecoverAndLogHandler.
  43. // NOTE: This function blocks - you may want to call it in a go-routine.
  44. func StartHTTPServer(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
  45. logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s", listener.Addr()))
  46. s := &http.Server{
  47. Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger),
  48. ReadTimeout: config.ReadTimeout,
  49. WriteTimeout: config.WriteTimeout,
  50. MaxHeaderBytes: maxHeaderBytes,
  51. }
  52. err := s.Serve(listener)
  53. logger.Info("RPC HTTP server stopped", "err", err)
  54. return err
  55. }
  56. // StartHTTPAndTLSServer takes a listener and starts an HTTPS server with the given handler.
  57. // It wraps handler with RecoverAndLogHandler.
  58. // NOTE: This function blocks - you may want to call it in a go-routine.
  59. func StartHTTPAndTLSServer(
  60. listener net.Listener,
  61. handler http.Handler,
  62. certFile, keyFile string,
  63. logger log.Logger,
  64. config *Config,
  65. ) error {
  66. logger.Info(fmt.Sprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)",
  67. listener.Addr(), certFile, keyFile))
  68. s := &http.Server{
  69. Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger),
  70. ReadTimeout: config.ReadTimeout,
  71. WriteTimeout: config.WriteTimeout,
  72. MaxHeaderBytes: maxHeaderBytes,
  73. }
  74. err := s.ServeTLS(listener, certFile, keyFile)
  75. logger.Error("RPC HTTPS server stopped", "err", err)
  76. return err
  77. }
  78. func WriteRPCResponseHTTPError(
  79. w http.ResponseWriter,
  80. httpCode int,
  81. res types.RPCResponse,
  82. ) {
  83. jsonBytes, err := json.MarshalIndent(res, "", " ")
  84. if err != nil {
  85. panic(err)
  86. }
  87. w.Header().Set("Content-Type", "application/json")
  88. w.WriteHeader(httpCode)
  89. if _, err := w.Write(jsonBytes); err != nil {
  90. panic(err)
  91. }
  92. }
  93. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  94. jsonBytes, err := json.MarshalIndent(res, "", " ")
  95. if err != nil {
  96. panic(err)
  97. }
  98. w.Header().Set("Content-Type", "application/json")
  99. w.WriteHeader(200)
  100. if _, err := w.Write(jsonBytes); err != nil {
  101. panic(err)
  102. }
  103. }
  104. // WriteRPCResponseArrayHTTP will do the same as WriteRPCResponseHTTP, except it
  105. // can write arrays of responses for batched request/response interactions via
  106. // the JSON RPC.
  107. func WriteRPCResponseArrayHTTP(w http.ResponseWriter, res []types.RPCResponse) {
  108. if len(res) == 1 {
  109. WriteRPCResponseHTTP(w, res[0])
  110. } else {
  111. jsonBytes, err := json.MarshalIndent(res, "", " ")
  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. //-----------------------------------------------------------------------------
  123. // RecoverAndLogHandler wraps an HTTP handler, adding error logging.
  124. // If the inner function panics, the outer function recovers, logs, sends an
  125. // HTTP 500 error response.
  126. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  127. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  128. // Wrap the ResponseWriter to remember the status
  129. rww := &ResponseWriterWrapper{-1, w}
  130. begin := time.Now()
  131. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  132. defer func() {
  133. // Send a 500 error if a panic happens during a handler.
  134. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  135. // at least to my localhost.
  136. if e := recover(); e != nil {
  137. // If RPCResponse
  138. if res, ok := e.(types.RPCResponse); ok {
  139. WriteRPCResponseHTTP(rww, res)
  140. } else {
  141. // For the rest,
  142. logger.Error(
  143. "Panic in RPC HTTP handler", "err", e, "stack",
  144. string(debug.Stack()),
  145. )
  146. WriteRPCResponseHTTPError(rww, http.StatusInternalServerError, types.RPCInternalError(types.JSONRPCStringID(""), e.(error)))
  147. }
  148. }
  149. // Finally, log.
  150. durationMS := time.Since(begin).Nanoseconds() / 1000000
  151. if rww.Status == -1 {
  152. rww.Status = 200
  153. }
  154. logger.Info("Served RPC HTTP response",
  155. "method", r.Method, "url", r.URL,
  156. "status", rww.Status, "duration", durationMS,
  157. "remoteAddr", r.RemoteAddr,
  158. )
  159. }()
  160. handler.ServeHTTP(rww, r)
  161. })
  162. }
  163. // Remember the status for logging
  164. type ResponseWriterWrapper struct {
  165. Status int
  166. http.ResponseWriter
  167. }
  168. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  169. w.Status = status
  170. w.ResponseWriter.WriteHeader(status)
  171. }
  172. // implements http.Hijacker
  173. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  174. return w.ResponseWriter.(http.Hijacker).Hijack()
  175. }
  176. type maxBytesHandler struct {
  177. h http.Handler
  178. n int64
  179. }
  180. func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  181. r.Body = http.MaxBytesReader(w, r.Body, h.n)
  182. h.h.ServeHTTP(w, r)
  183. }
  184. // Listen starts a new net.Listener on the given address.
  185. // It returns an error if the address is invalid or the call to Listen() fails.
  186. func Listen(addr string, config *Config) (listener net.Listener, err error) {
  187. parts := strings.SplitN(addr, "://", 2)
  188. if len(parts) != 2 {
  189. return nil, errors.Errorf(
  190. "invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
  191. addr,
  192. )
  193. }
  194. proto, addr := parts[0], parts[1]
  195. listener, err = net.Listen(proto, addr)
  196. if err != nil {
  197. return nil, errors.Errorf("failed to listen on %v: %v", addr, err)
  198. }
  199. if config.MaxOpenConnections > 0 {
  200. listener = netutil.LimitListener(listener, config.MaxOpenConnections)
  201. }
  202. return listener, nil
  203. }