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.

423 lines
11 KiB

9 years ago
9 years ago
9 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. "sync"
  11. "time"
  12. "github.com/tendermint/tendermint/abci/types"
  13. "github.com/tendermint/tendermint/libs/log"
  14. tmnet "github.com/tendermint/tendermint/libs/net"
  15. "github.com/tendermint/tendermint/libs/service"
  16. )
  17. const (
  18. // reqQueueSize is the max number of queued async requests.
  19. // (memory: 256MB max assuming 1MB transactions)
  20. reqQueueSize = 256
  21. )
  22. // This is goroutine-safe, but users should beware that the application in
  23. // general is not meant to be interfaced with concurrent callers.
  24. type socketClient struct {
  25. service.BaseService
  26. logger log.Logger
  27. addr string
  28. mustConnect bool
  29. conn net.Conn
  30. reqQueue chan *requestAndResponse
  31. mtx sync.Mutex
  32. err error
  33. reqSent *list.List // list of requests sent, waiting for response
  34. }
  35. var _ Client = (*socketClient)(nil)
  36. // NewSocketClient creates a new socket client, which connects to a given
  37. // address. If mustConnect is true, the client will return an error upon start
  38. // if it fails to connect.
  39. func NewSocketClient(logger log.Logger, addr string, mustConnect bool) Client {
  40. cli := &socketClient{
  41. logger: logger,
  42. reqQueue: make(chan *requestAndResponse, reqQueueSize),
  43. mustConnect: mustConnect,
  44. addr: addr,
  45. reqSent: list.New(),
  46. }
  47. cli.BaseService = *service.NewBaseService(logger, "socketClient", cli)
  48. return cli
  49. }
  50. // OnStart implements Service by connecting to the server and spawning reading
  51. // and writing goroutines.
  52. func (cli *socketClient) OnStart(ctx context.Context) error {
  53. var (
  54. err error
  55. conn net.Conn
  56. )
  57. for {
  58. conn, err = tmnet.Connect(cli.addr)
  59. if err != nil {
  60. if cli.mustConnect {
  61. return err
  62. }
  63. cli.logger.Error(fmt.Sprintf("abci.socketClient failed to connect to %v. Retrying after %vs...",
  64. cli.addr, dialRetryIntervalSeconds), "err", err)
  65. time.Sleep(time.Second * dialRetryIntervalSeconds)
  66. continue
  67. }
  68. cli.conn = conn
  69. go cli.sendRequestsRoutine(ctx, conn)
  70. go cli.recvResponseRoutine(ctx, conn)
  71. return nil
  72. }
  73. }
  74. // OnStop implements Service by closing connection and flushing all queues.
  75. func (cli *socketClient) OnStop() {
  76. if cli.conn != nil {
  77. cli.conn.Close()
  78. }
  79. // this timeout is arbitrary.
  80. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  81. defer cancel()
  82. cli.drainQueue(ctx)
  83. }
  84. // Error returns an error if the client was stopped abruptly.
  85. func (cli *socketClient) Error() error {
  86. cli.mtx.Lock()
  87. defer cli.mtx.Unlock()
  88. return cli.err
  89. }
  90. //----------------------------------------
  91. func (cli *socketClient) sendRequestsRoutine(ctx context.Context, conn io.Writer) {
  92. bw := bufio.NewWriter(conn)
  93. for {
  94. select {
  95. case <-ctx.Done():
  96. return
  97. case reqres := <-cli.reqQueue:
  98. if ctx.Err() != nil {
  99. return
  100. }
  101. cli.willSendReq(reqres)
  102. if err := types.WriteMessage(reqres.Request, bw); err != nil {
  103. cli.stopForError(fmt.Errorf("write to buffer: %w", err))
  104. return
  105. }
  106. if err := bw.Flush(); err != nil {
  107. cli.stopForError(fmt.Errorf("flush buffer: %w", err))
  108. return
  109. }
  110. }
  111. }
  112. }
  113. func (cli *socketClient) recvResponseRoutine(ctx context.Context, conn io.Reader) {
  114. r := bufio.NewReader(conn)
  115. for {
  116. if ctx.Err() != nil {
  117. return
  118. }
  119. res := &types.Response{}
  120. if err := types.ReadMessage(r, res); err != nil {
  121. cli.stopForError(fmt.Errorf("read message: %w", err))
  122. return
  123. }
  124. switch r := res.Value.(type) {
  125. case *types.Response_Exception: // app responded with error
  126. // XXX After setting cli.err, release waiters (e.g. reqres.Done())
  127. cli.stopForError(errors.New(r.Exception.Error))
  128. return
  129. default:
  130. if err := cli.didRecvResponse(res); err != nil {
  131. cli.stopForError(err)
  132. return
  133. }
  134. }
  135. }
  136. }
  137. func (cli *socketClient) willSendReq(reqres *requestAndResponse) {
  138. cli.mtx.Lock()
  139. defer cli.mtx.Unlock()
  140. cli.reqSent.PushBack(reqres)
  141. }
  142. func (cli *socketClient) didRecvResponse(res *types.Response) error {
  143. cli.mtx.Lock()
  144. defer cli.mtx.Unlock()
  145. // Get the first ReqRes.
  146. next := cli.reqSent.Front()
  147. if next == nil {
  148. return fmt.Errorf("unexpected %T when nothing expected", res.Value)
  149. }
  150. reqres := next.Value.(*requestAndResponse)
  151. if !resMatchesReq(reqres.Request, res) {
  152. return fmt.Errorf("unexpected %T when response to %T expected", res.Value, reqres.Request.Value)
  153. }
  154. reqres.Response = res
  155. reqres.markDone() // release waiters
  156. cli.reqSent.Remove(next) // pop first item from linked list
  157. return nil
  158. }
  159. //----------------------------------------
  160. func (cli *socketClient) Flush(ctx context.Context) error {
  161. _, err := cli.doRequest(ctx, types.ToRequestFlush())
  162. if err != nil {
  163. return err
  164. }
  165. return nil
  166. }
  167. func (cli *socketClient) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) {
  168. res, err := cli.doRequest(ctx, types.ToRequestEcho(msg))
  169. if err != nil {
  170. return nil, err
  171. }
  172. return res.GetEcho(), nil
  173. }
  174. func (cli *socketClient) Info(ctx context.Context, req types.RequestInfo) (*types.ResponseInfo, error) {
  175. res, err := cli.doRequest(ctx, types.ToRequestInfo(req))
  176. if err != nil {
  177. return nil, err
  178. }
  179. return res.GetInfo(), nil
  180. }
  181. func (cli *socketClient) CheckTx(ctx context.Context, req types.RequestCheckTx) (*types.ResponseCheckTx, error) {
  182. res, err := cli.doRequest(ctx, types.ToRequestCheckTx(req))
  183. if err != nil {
  184. return nil, err
  185. }
  186. return res.GetCheckTx(), nil
  187. }
  188. func (cli *socketClient) Query(ctx context.Context, req types.RequestQuery) (*types.ResponseQuery, error) {
  189. res, err := cli.doRequest(ctx, types.ToRequestQuery(req))
  190. if err != nil {
  191. return nil, err
  192. }
  193. return res.GetQuery(), nil
  194. }
  195. func (cli *socketClient) Commit(ctx context.Context) (*types.ResponseCommit, error) {
  196. res, err := cli.doRequest(ctx, types.ToRequestCommit())
  197. if err != nil {
  198. return nil, err
  199. }
  200. return res.GetCommit(), nil
  201. }
  202. func (cli *socketClient) InitChain(ctx context.Context, req types.RequestInitChain) (*types.ResponseInitChain, error) {
  203. res, err := cli.doRequest(ctx, types.ToRequestInitChain(req))
  204. if err != nil {
  205. return nil, err
  206. }
  207. return res.GetInitChain(), nil
  208. }
  209. func (cli *socketClient) ListSnapshots(ctx context.Context, req types.RequestListSnapshots) (*types.ResponseListSnapshots, error) {
  210. res, err := cli.doRequest(ctx, types.ToRequestListSnapshots(req))
  211. if err != nil {
  212. return nil, err
  213. }
  214. return res.GetListSnapshots(), nil
  215. }
  216. func (cli *socketClient) OfferSnapshot(ctx context.Context, req types.RequestOfferSnapshot) (*types.ResponseOfferSnapshot, error) {
  217. res, err := cli.doRequest(ctx, types.ToRequestOfferSnapshot(req))
  218. if err != nil {
  219. return nil, err
  220. }
  221. return res.GetOfferSnapshot(), nil
  222. }
  223. func (cli *socketClient) LoadSnapshotChunk(ctx context.Context, req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
  224. res, err := cli.doRequest(ctx, types.ToRequestLoadSnapshotChunk(req))
  225. if err != nil {
  226. return nil, err
  227. }
  228. return res.GetLoadSnapshotChunk(), nil
  229. }
  230. func (cli *socketClient) ApplySnapshotChunk(ctx context.Context, req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
  231. res, err := cli.doRequest(ctx, types.ToRequestApplySnapshotChunk(req))
  232. if err != nil {
  233. return nil, err
  234. }
  235. return res.GetApplySnapshotChunk(), nil
  236. }
  237. func (cli *socketClient) PrepareProposal(ctx context.Context, req types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) {
  238. res, err := cli.doRequest(ctx, types.ToRequestPrepareProposal(req))
  239. if err != nil {
  240. return nil, err
  241. }
  242. return res.GetPrepareProposal(), nil
  243. }
  244. func (cli *socketClient) ProcessProposal(ctx context.Context, req types.RequestProcessProposal) (*types.ResponseProcessProposal, error) {
  245. res, err := cli.doRequest(ctx, types.ToRequestProcessProposal(req))
  246. if err != nil {
  247. return nil, err
  248. }
  249. return res.GetProcessProposal(), nil
  250. }
  251. func (cli *socketClient) ExtendVote(ctx context.Context, req types.RequestExtendVote) (*types.ResponseExtendVote, error) {
  252. res, err := cli.doRequest(ctx, types.ToRequestExtendVote(req))
  253. if err != nil {
  254. return nil, err
  255. }
  256. return res.GetExtendVote(), nil
  257. }
  258. func (cli *socketClient) VerifyVoteExtension(ctx context.Context, req types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) {
  259. res, err := cli.doRequest(ctx, types.ToRequestVerifyVoteExtension(req))
  260. if err != nil {
  261. return nil, err
  262. }
  263. return res.GetVerifyVoteExtension(), nil
  264. }
  265. func (cli *socketClient) FinalizeBlock(ctx context.Context, req types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) {
  266. res, err := cli.doRequest(ctx, types.ToRequestFinalizeBlock(req))
  267. if err != nil {
  268. return nil, err
  269. }
  270. return res.GetFinalizeBlock(), nil
  271. }
  272. //----------------------------------------
  273. func (cli *socketClient) doRequest(ctx context.Context, req *types.Request) (*types.Response, error) {
  274. reqres := makeReqRes(req)
  275. select {
  276. case cli.reqQueue <- reqres:
  277. case <-ctx.Done():
  278. return nil, fmt.Errorf("can't queue req: %w", ctx.Err())
  279. }
  280. select {
  281. case <-reqres.signal:
  282. if err := cli.Error(); err != nil {
  283. return nil, err
  284. }
  285. return reqres.Response, nil
  286. case <-ctx.Done():
  287. return nil, ctx.Err()
  288. }
  289. }
  290. // drainQueue marks as complete and discards all remaining pending requests
  291. // from the queue.
  292. func (cli *socketClient) drainQueue(ctx context.Context) {
  293. cli.mtx.Lock()
  294. defer cli.mtx.Unlock()
  295. // mark all in-flight messages as resolved (they will get cli.Error())
  296. for req := cli.reqSent.Front(); req != nil; req = req.Next() {
  297. reqres := req.Value.(*requestAndResponse)
  298. reqres.markDone()
  299. }
  300. // Mark all queued messages as resolved.
  301. //
  302. // TODO(creachadair): We can't simply range the channel, because it is never
  303. // closed, and the writer continues to add work.
  304. // See https://github.com/tendermint/tendermint/issues/6996.
  305. for {
  306. select {
  307. case <-ctx.Done():
  308. return
  309. case reqres := <-cli.reqQueue:
  310. reqres.markDone()
  311. default:
  312. return
  313. }
  314. }
  315. }
  316. //----------------------------------------
  317. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  318. switch req.Value.(type) {
  319. case *types.Request_Echo:
  320. _, ok = res.Value.(*types.Response_Echo)
  321. case *types.Request_Flush:
  322. _, ok = res.Value.(*types.Response_Flush)
  323. case *types.Request_Info:
  324. _, ok = res.Value.(*types.Response_Info)
  325. case *types.Request_CheckTx:
  326. _, ok = res.Value.(*types.Response_CheckTx)
  327. case *types.Request_Commit:
  328. _, ok = res.Value.(*types.Response_Commit)
  329. case *types.Request_Query:
  330. _, ok = res.Value.(*types.Response_Query)
  331. case *types.Request_InitChain:
  332. _, ok = res.Value.(*types.Response_InitChain)
  333. case *types.Request_ProcessProposal:
  334. _, ok = res.Value.(*types.Response_ProcessProposal)
  335. case *types.Request_PrepareProposal:
  336. _, ok = res.Value.(*types.Response_PrepareProposal)
  337. case *types.Request_ExtendVote:
  338. _, ok = res.Value.(*types.Response_ExtendVote)
  339. case *types.Request_VerifyVoteExtension:
  340. _, ok = res.Value.(*types.Response_VerifyVoteExtension)
  341. case *types.Request_ApplySnapshotChunk:
  342. _, ok = res.Value.(*types.Response_ApplySnapshotChunk)
  343. case *types.Request_LoadSnapshotChunk:
  344. _, ok = res.Value.(*types.Response_LoadSnapshotChunk)
  345. case *types.Request_ListSnapshots:
  346. _, ok = res.Value.(*types.Response_ListSnapshots)
  347. case *types.Request_OfferSnapshot:
  348. _, ok = res.Value.(*types.Response_OfferSnapshot)
  349. case *types.Request_FinalizeBlock:
  350. _, ok = res.Value.(*types.Response_FinalizeBlock)
  351. }
  352. return ok
  353. }
  354. func (cli *socketClient) stopForError(err error) {
  355. if !cli.IsRunning() {
  356. return
  357. }
  358. cli.mtx.Lock()
  359. cli.err = err
  360. cli.mtx.Unlock()
  361. cli.logger.Info("Stopping abci.socketClient", "reason", err)
  362. cli.Stop()
  363. }