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.

559 lines
14 KiB

8 years ago
8 years ago
8 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
  1. package abciclient
  2. import (
  3. "bufio"
  4. "container/list"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "reflect"
  11. "sync"
  12. "time"
  13. "github.com/tendermint/tendermint/abci/types"
  14. "github.com/tendermint/tendermint/libs/log"
  15. tmnet "github.com/tendermint/tendermint/libs/net"
  16. "github.com/tendermint/tendermint/libs/service"
  17. )
  18. const (
  19. // reqQueueSize is the max number of queued async requests.
  20. // (memory: 256MB max assuming 1MB transactions)
  21. reqQueueSize = 256
  22. )
  23. // This is goroutine-safe, but users should beware that the application in
  24. // general is not meant to be interfaced with concurrent callers.
  25. type socketClient struct {
  26. service.BaseService
  27. logger log.Logger
  28. addr string
  29. mustConnect bool
  30. conn net.Conn
  31. reqQueue chan *ReqRes
  32. mtx sync.Mutex
  33. err error
  34. reqSent *list.List // list of requests sent, waiting for response
  35. resCb func(*types.Request, *types.Response) // called on all requests, if set.
  36. }
  37. var _ Client = (*socketClient)(nil)
  38. // NewSocketClient creates a new socket client, which connects to a given
  39. // address. If mustConnect is true, the client will return an error upon start
  40. // if it fails to connect.
  41. func NewSocketClient(logger log.Logger, addr string, mustConnect bool) Client {
  42. cli := &socketClient{
  43. logger: logger,
  44. reqQueue: make(chan *ReqRes, reqQueueSize),
  45. mustConnect: mustConnect,
  46. addr: addr,
  47. reqSent: list.New(),
  48. resCb: nil,
  49. }
  50. cli.BaseService = *service.NewBaseService(logger, "socketClient", cli)
  51. return cli
  52. }
  53. // OnStart implements Service by connecting to the server and spawning reading
  54. // and writing goroutines.
  55. func (cli *socketClient) OnStart(ctx context.Context) error {
  56. var (
  57. err error
  58. conn net.Conn
  59. )
  60. for {
  61. conn, err = tmnet.Connect(cli.addr)
  62. if err != nil {
  63. if cli.mustConnect {
  64. return err
  65. }
  66. cli.logger.Error(fmt.Sprintf("abci.socketClient failed to connect to %v. Retrying after %vs...",
  67. cli.addr, dialRetryIntervalSeconds), "err", err)
  68. time.Sleep(time.Second * dialRetryIntervalSeconds)
  69. continue
  70. }
  71. cli.conn = conn
  72. go cli.sendRequestsRoutine(ctx, conn)
  73. go cli.recvResponseRoutine(ctx, conn)
  74. return nil
  75. }
  76. }
  77. // OnStop implements Service by closing connection and flushing all queues.
  78. func (cli *socketClient) OnStop() {
  79. if cli.conn != nil {
  80. cli.conn.Close()
  81. }
  82. // this timeout is arbitrary.
  83. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  84. defer cancel()
  85. cli.drainQueue(ctx)
  86. }
  87. // Error returns an error if the client was stopped abruptly.
  88. func (cli *socketClient) Error() error {
  89. cli.mtx.Lock()
  90. defer cli.mtx.Unlock()
  91. return cli.err
  92. }
  93. // SetResponseCallback sets a callback, which will be executed for each
  94. // non-error & non-empty response from the server.
  95. //
  96. // NOTE: callback may get internally generated flush responses.
  97. func (cli *socketClient) SetResponseCallback(resCb Callback) {
  98. cli.mtx.Lock()
  99. defer cli.mtx.Unlock()
  100. cli.resCb = resCb
  101. }
  102. //----------------------------------------
  103. func (cli *socketClient) sendRequestsRoutine(ctx context.Context, conn io.Writer) {
  104. bw := bufio.NewWriter(conn)
  105. for {
  106. select {
  107. case <-ctx.Done():
  108. return
  109. case reqres := <-cli.reqQueue:
  110. if ctx.Err() != nil {
  111. return
  112. }
  113. cli.willSendReq(reqres)
  114. if err := types.WriteMessage(reqres.Request, bw); err != nil {
  115. cli.stopForError(fmt.Errorf("write to buffer: %w", err))
  116. return
  117. }
  118. if err := bw.Flush(); err != nil {
  119. cli.stopForError(fmt.Errorf("flush buffer: %w", err))
  120. return
  121. }
  122. }
  123. }
  124. }
  125. func (cli *socketClient) recvResponseRoutine(ctx context.Context, conn io.Reader) {
  126. r := bufio.NewReader(conn)
  127. for {
  128. if ctx.Err() != nil {
  129. return
  130. }
  131. var res = &types.Response{}
  132. err := types.ReadMessage(r, res)
  133. if err != nil {
  134. cli.stopForError(fmt.Errorf("read message: %w", err))
  135. return
  136. }
  137. // cli.logger.Debug("Received response", "responseType", reflect.TypeOf(res), "response", res)
  138. switch r := res.Value.(type) {
  139. case *types.Response_Exception: // app responded with error
  140. // XXX After setting cli.err, release waiters (e.g. reqres.Done())
  141. cli.stopForError(errors.New(r.Exception.Error))
  142. return
  143. default:
  144. err := cli.didRecvResponse(res)
  145. if err != nil {
  146. cli.stopForError(err)
  147. return
  148. }
  149. }
  150. }
  151. }
  152. func (cli *socketClient) willSendReq(reqres *ReqRes) {
  153. cli.mtx.Lock()
  154. defer cli.mtx.Unlock()
  155. cli.reqSent.PushBack(reqres)
  156. }
  157. func (cli *socketClient) didRecvResponse(res *types.Response) error {
  158. cli.mtx.Lock()
  159. defer cli.mtx.Unlock()
  160. // Get the first ReqRes.
  161. next := cli.reqSent.Front()
  162. if next == nil {
  163. return fmt.Errorf("unexpected %v when nothing expected", reflect.TypeOf(res.Value))
  164. }
  165. reqres := next.Value.(*ReqRes)
  166. if !resMatchesReq(reqres.Request, res) {
  167. return fmt.Errorf("unexpected %v when response to %v expected",
  168. reflect.TypeOf(res.Value), reflect.TypeOf(reqres.Request.Value))
  169. }
  170. reqres.Response = res
  171. reqres.Done() // release waiters
  172. cli.reqSent.Remove(next) // pop first item from linked list
  173. // Notify client listener if set (global callback).
  174. if cli.resCb != nil {
  175. cli.resCb(reqres.Request, res)
  176. }
  177. // Notify reqRes listener if set (request specific callback).
  178. //
  179. // NOTE: It is possible this callback isn't set on the reqres object. At this
  180. // point, in which case it will be called after, when it is set.
  181. reqres.InvokeCallback()
  182. return nil
  183. }
  184. //----------------------------------------
  185. func (cli *socketClient) FlushAsync(ctx context.Context) (*ReqRes, error) {
  186. return cli.queueRequestAsync(ctx, types.ToRequestFlush())
  187. }
  188. func (cli *socketClient) CheckTxAsync(ctx context.Context, req types.RequestCheckTx) (*ReqRes, error) {
  189. return cli.queueRequestAsync(ctx, types.ToRequestCheckTx(req))
  190. }
  191. //----------------------------------------
  192. func (cli *socketClient) Flush(ctx context.Context) error {
  193. reqRes, err := cli.queueRequest(ctx, types.ToRequestFlush(), true)
  194. if err != nil {
  195. return queueErr(err)
  196. }
  197. if err := cli.Error(); err != nil {
  198. return err
  199. }
  200. gotResp := make(chan struct{})
  201. go func() {
  202. // NOTE: if we don't flush the queue, its possible to get stuck here
  203. reqRes.Wait()
  204. close(gotResp)
  205. }()
  206. select {
  207. case <-gotResp:
  208. return cli.Error()
  209. case <-ctx.Done():
  210. return ctx.Err()
  211. }
  212. }
  213. func (cli *socketClient) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) {
  214. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestEcho(msg))
  215. if err != nil {
  216. return nil, err
  217. }
  218. return reqres.Response.GetEcho(), nil
  219. }
  220. func (cli *socketClient) Info(
  221. ctx context.Context,
  222. req types.RequestInfo,
  223. ) (*types.ResponseInfo, error) {
  224. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestInfo(req))
  225. if err != nil {
  226. return nil, err
  227. }
  228. return reqres.Response.GetInfo(), nil
  229. }
  230. func (cli *socketClient) CheckTx(
  231. ctx context.Context,
  232. req types.RequestCheckTx,
  233. ) (*types.ResponseCheckTx, error) {
  234. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestCheckTx(req))
  235. if err != nil {
  236. return nil, err
  237. }
  238. return reqres.Response.GetCheckTx(), nil
  239. }
  240. func (cli *socketClient) Query(
  241. ctx context.Context,
  242. req types.RequestQuery,
  243. ) (*types.ResponseQuery, error) {
  244. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestQuery(req))
  245. if err != nil {
  246. return nil, err
  247. }
  248. return reqres.Response.GetQuery(), nil
  249. }
  250. func (cli *socketClient) Commit(ctx context.Context) (*types.ResponseCommit, error) {
  251. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestCommit())
  252. if err != nil {
  253. return nil, err
  254. }
  255. return reqres.Response.GetCommit(), nil
  256. }
  257. func (cli *socketClient) InitChain(
  258. ctx context.Context,
  259. req types.RequestInitChain,
  260. ) (*types.ResponseInitChain, error) {
  261. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestInitChain(req))
  262. if err != nil {
  263. return nil, err
  264. }
  265. return reqres.Response.GetInitChain(), nil
  266. }
  267. func (cli *socketClient) ListSnapshots(
  268. ctx context.Context,
  269. req types.RequestListSnapshots,
  270. ) (*types.ResponseListSnapshots, error) {
  271. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestListSnapshots(req))
  272. if err != nil {
  273. return nil, err
  274. }
  275. return reqres.Response.GetListSnapshots(), nil
  276. }
  277. func (cli *socketClient) OfferSnapshot(
  278. ctx context.Context,
  279. req types.RequestOfferSnapshot,
  280. ) (*types.ResponseOfferSnapshot, error) {
  281. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestOfferSnapshot(req))
  282. if err != nil {
  283. return nil, err
  284. }
  285. return reqres.Response.GetOfferSnapshot(), nil
  286. }
  287. func (cli *socketClient) LoadSnapshotChunk(
  288. ctx context.Context,
  289. req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
  290. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestLoadSnapshotChunk(req))
  291. if err != nil {
  292. return nil, err
  293. }
  294. return reqres.Response.GetLoadSnapshotChunk(), nil
  295. }
  296. func (cli *socketClient) ApplySnapshotChunk(
  297. ctx context.Context,
  298. req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
  299. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestApplySnapshotChunk(req))
  300. if err != nil {
  301. return nil, err
  302. }
  303. return reqres.Response.GetApplySnapshotChunk(), nil
  304. }
  305. func (cli *socketClient) PrepareProposal(
  306. ctx context.Context,
  307. req types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) {
  308. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestPrepareProposal(req))
  309. if err != nil {
  310. return nil, err
  311. }
  312. return reqres.Response.GetPrepareProposal(), nil
  313. }
  314. func (cli *socketClient) ProcessProposal(
  315. ctx context.Context,
  316. req types.RequestProcessProposal,
  317. ) (*types.ResponseProcessProposal, error) {
  318. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestProcessProposal(req))
  319. if err != nil {
  320. return nil, err
  321. }
  322. return reqres.Response.GetProcessProposal(), nil
  323. }
  324. func (cli *socketClient) ExtendVote(
  325. ctx context.Context,
  326. req types.RequestExtendVote) (*types.ResponseExtendVote, error) {
  327. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestExtendVote(req))
  328. if err != nil {
  329. return nil, err
  330. }
  331. return reqres.Response.GetExtendVote(), nil
  332. }
  333. func (cli *socketClient) VerifyVoteExtension(
  334. ctx context.Context,
  335. req types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) {
  336. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestVerifyVoteExtension(req))
  337. if err != nil {
  338. return nil, err
  339. }
  340. return reqres.Response.GetVerifyVoteExtension(), nil
  341. }
  342. func (cli *socketClient) FinalizeBlock(
  343. ctx context.Context,
  344. req types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) {
  345. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestFinalizeBlock(req))
  346. if err != nil {
  347. return nil, err
  348. }
  349. return reqres.Response.GetFinalizeBlock(), nil
  350. }
  351. //----------------------------------------
  352. // queueRequest enqueues req onto the queue. If the queue is full, it ether
  353. // returns an error (sync=false) or blocks (sync=true).
  354. //
  355. // When sync=true, ctx can be used to break early. When sync=false, ctx will be
  356. // used later to determine if request should be dropped (if ctx.Err is
  357. // non-nil).
  358. //
  359. // The caller is responsible for checking cli.Error.
  360. func (cli *socketClient) queueRequest(ctx context.Context, req *types.Request, sync bool) (*ReqRes, error) {
  361. reqres := NewReqRes(req)
  362. if sync {
  363. select {
  364. case cli.reqQueue <- reqres:
  365. case <-ctx.Done():
  366. return nil, ctx.Err()
  367. }
  368. } else {
  369. select {
  370. case cli.reqQueue <- reqres:
  371. default:
  372. return nil, errors.New("buffer is full")
  373. }
  374. }
  375. return reqres, nil
  376. }
  377. func (cli *socketClient) queueRequestAsync(
  378. ctx context.Context,
  379. req *types.Request,
  380. ) (*ReqRes, error) {
  381. reqres, err := cli.queueRequest(ctx, req, false)
  382. if err != nil {
  383. return nil, queueErr(err)
  384. }
  385. return reqres, cli.Error()
  386. }
  387. func (cli *socketClient) queueRequestAndFlush(
  388. ctx context.Context,
  389. req *types.Request,
  390. ) (*ReqRes, error) {
  391. reqres, err := cli.queueRequest(ctx, req, true)
  392. if err != nil {
  393. return nil, queueErr(err)
  394. }
  395. if err := cli.Flush(ctx); err != nil {
  396. return nil, err
  397. }
  398. return reqres, cli.Error()
  399. }
  400. func queueErr(e error) error {
  401. return fmt.Errorf("can't queue req: %w", e)
  402. }
  403. // drainQueue marks as complete and discards all remaining pending requests
  404. // from the queue.
  405. func (cli *socketClient) drainQueue(ctx context.Context) {
  406. cli.mtx.Lock()
  407. defer cli.mtx.Unlock()
  408. // mark all in-flight messages as resolved (they will get cli.Error())
  409. for req := cli.reqSent.Front(); req != nil; req = req.Next() {
  410. reqres := req.Value.(*ReqRes)
  411. reqres.Done()
  412. }
  413. // Mark all queued messages as resolved.
  414. //
  415. // TODO(creachadair): We can't simply range the channel, because it is never
  416. // closed, and the writer continues to add work.
  417. // See https://github.com/tendermint/tendermint/issues/6996.
  418. for {
  419. select {
  420. case <-ctx.Done():
  421. return
  422. case reqres := <-cli.reqQueue:
  423. reqres.Done()
  424. default:
  425. return
  426. }
  427. }
  428. }
  429. //----------------------------------------
  430. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  431. switch req.Value.(type) {
  432. case *types.Request_Echo:
  433. _, ok = res.Value.(*types.Response_Echo)
  434. case *types.Request_Flush:
  435. _, ok = res.Value.(*types.Response_Flush)
  436. case *types.Request_Info:
  437. _, ok = res.Value.(*types.Response_Info)
  438. case *types.Request_CheckTx:
  439. _, ok = res.Value.(*types.Response_CheckTx)
  440. case *types.Request_Commit:
  441. _, ok = res.Value.(*types.Response_Commit)
  442. case *types.Request_Query:
  443. _, ok = res.Value.(*types.Response_Query)
  444. case *types.Request_InitChain:
  445. _, ok = res.Value.(*types.Response_InitChain)
  446. case *types.Request_PrepareProposal:
  447. _, ok = res.Value.(*types.Response_PrepareProposal)
  448. case *types.Request_ExtendVote:
  449. _, ok = res.Value.(*types.Response_ExtendVote)
  450. case *types.Request_VerifyVoteExtension:
  451. _, ok = res.Value.(*types.Response_VerifyVoteExtension)
  452. case *types.Request_ApplySnapshotChunk:
  453. _, ok = res.Value.(*types.Response_ApplySnapshotChunk)
  454. case *types.Request_LoadSnapshotChunk:
  455. _, ok = res.Value.(*types.Response_LoadSnapshotChunk)
  456. case *types.Request_ListSnapshots:
  457. _, ok = res.Value.(*types.Response_ListSnapshots)
  458. case *types.Request_OfferSnapshot:
  459. _, ok = res.Value.(*types.Response_OfferSnapshot)
  460. case *types.Request_FinalizeBlock:
  461. _, ok = res.Value.(*types.Response_FinalizeBlock)
  462. }
  463. return ok
  464. }
  465. func (cli *socketClient) stopForError(err error) {
  466. if !cli.IsRunning() {
  467. return
  468. }
  469. cli.mtx.Lock()
  470. cli.err = err
  471. cli.mtx.Unlock()
  472. cli.logger.Info("Stopping abci.socketClient", "reason", err)
  473. cli.Stop()
  474. }