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.

552 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.SetDone() // 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. select {
  201. case <-reqRes.signal:
  202. return cli.Error()
  203. case <-ctx.Done():
  204. return ctx.Err()
  205. }
  206. }
  207. func (cli *socketClient) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) {
  208. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestEcho(msg))
  209. if err != nil {
  210. return nil, err
  211. }
  212. return reqres.Response.GetEcho(), nil
  213. }
  214. func (cli *socketClient) Info(
  215. ctx context.Context,
  216. req types.RequestInfo,
  217. ) (*types.ResponseInfo, error) {
  218. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestInfo(req))
  219. if err != nil {
  220. return nil, err
  221. }
  222. return reqres.Response.GetInfo(), nil
  223. }
  224. func (cli *socketClient) CheckTx(
  225. ctx context.Context,
  226. req types.RequestCheckTx,
  227. ) (*types.ResponseCheckTx, error) {
  228. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestCheckTx(req))
  229. if err != nil {
  230. return nil, err
  231. }
  232. return reqres.Response.GetCheckTx(), nil
  233. }
  234. func (cli *socketClient) Query(
  235. ctx context.Context,
  236. req types.RequestQuery,
  237. ) (*types.ResponseQuery, error) {
  238. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestQuery(req))
  239. if err != nil {
  240. return nil, err
  241. }
  242. return reqres.Response.GetQuery(), nil
  243. }
  244. func (cli *socketClient) Commit(ctx context.Context) (*types.ResponseCommit, error) {
  245. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestCommit())
  246. if err != nil {
  247. return nil, err
  248. }
  249. return reqres.Response.GetCommit(), nil
  250. }
  251. func (cli *socketClient) InitChain(
  252. ctx context.Context,
  253. req types.RequestInitChain,
  254. ) (*types.ResponseInitChain, error) {
  255. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestInitChain(req))
  256. if err != nil {
  257. return nil, err
  258. }
  259. return reqres.Response.GetInitChain(), nil
  260. }
  261. func (cli *socketClient) ListSnapshots(
  262. ctx context.Context,
  263. req types.RequestListSnapshots,
  264. ) (*types.ResponseListSnapshots, error) {
  265. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestListSnapshots(req))
  266. if err != nil {
  267. return nil, err
  268. }
  269. return reqres.Response.GetListSnapshots(), nil
  270. }
  271. func (cli *socketClient) OfferSnapshot(
  272. ctx context.Context,
  273. req types.RequestOfferSnapshot,
  274. ) (*types.ResponseOfferSnapshot, error) {
  275. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestOfferSnapshot(req))
  276. if err != nil {
  277. return nil, err
  278. }
  279. return reqres.Response.GetOfferSnapshot(), nil
  280. }
  281. func (cli *socketClient) LoadSnapshotChunk(
  282. ctx context.Context,
  283. req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
  284. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestLoadSnapshotChunk(req))
  285. if err != nil {
  286. return nil, err
  287. }
  288. return reqres.Response.GetLoadSnapshotChunk(), nil
  289. }
  290. func (cli *socketClient) ApplySnapshotChunk(
  291. ctx context.Context,
  292. req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
  293. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestApplySnapshotChunk(req))
  294. if err != nil {
  295. return nil, err
  296. }
  297. return reqres.Response.GetApplySnapshotChunk(), nil
  298. }
  299. func (cli *socketClient) PrepareProposal(
  300. ctx context.Context,
  301. req types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) {
  302. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestPrepareProposal(req))
  303. if err != nil {
  304. return nil, err
  305. }
  306. return reqres.Response.GetPrepareProposal(), nil
  307. }
  308. func (cli *socketClient) ProcessProposal(
  309. ctx context.Context,
  310. req types.RequestProcessProposal,
  311. ) (*types.ResponseProcessProposal, error) {
  312. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestProcessProposal(req))
  313. if err != nil {
  314. return nil, err
  315. }
  316. return reqres.Response.GetProcessProposal(), nil
  317. }
  318. func (cli *socketClient) ExtendVote(
  319. ctx context.Context,
  320. req types.RequestExtendVote) (*types.ResponseExtendVote, error) {
  321. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestExtendVote(req))
  322. if err != nil {
  323. return nil, err
  324. }
  325. return reqres.Response.GetExtendVote(), nil
  326. }
  327. func (cli *socketClient) VerifyVoteExtension(
  328. ctx context.Context,
  329. req types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) {
  330. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestVerifyVoteExtension(req))
  331. if err != nil {
  332. return nil, err
  333. }
  334. return reqres.Response.GetVerifyVoteExtension(), nil
  335. }
  336. func (cli *socketClient) FinalizeBlock(
  337. ctx context.Context,
  338. req types.RequestFinalizeBlock) (*types.ResponseFinalizeBlock, error) {
  339. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestFinalizeBlock(req))
  340. if err != nil {
  341. return nil, err
  342. }
  343. return reqres.Response.GetFinalizeBlock(), nil
  344. }
  345. //----------------------------------------
  346. // queueRequest enqueues req onto the queue. If the queue is full, it ether
  347. // returns an error (sync=false) or blocks (sync=true).
  348. //
  349. // When sync=true, ctx can be used to break early. When sync=false, ctx will be
  350. // used later to determine if request should be dropped (if ctx.Err is
  351. // non-nil).
  352. //
  353. // The caller is responsible for checking cli.Error.
  354. func (cli *socketClient) queueRequest(ctx context.Context, req *types.Request, sync bool) (*ReqRes, error) {
  355. reqres := NewReqRes(req)
  356. if sync {
  357. select {
  358. case cli.reqQueue <- reqres:
  359. case <-ctx.Done():
  360. return nil, ctx.Err()
  361. }
  362. } else {
  363. select {
  364. case cli.reqQueue <- reqres:
  365. default:
  366. return nil, errors.New("buffer is full")
  367. }
  368. }
  369. return reqres, nil
  370. }
  371. func (cli *socketClient) queueRequestAsync(
  372. ctx context.Context,
  373. req *types.Request,
  374. ) (*ReqRes, error) {
  375. reqres, err := cli.queueRequest(ctx, req, false)
  376. if err != nil {
  377. return nil, queueErr(err)
  378. }
  379. return reqres, cli.Error()
  380. }
  381. func (cli *socketClient) queueRequestAndFlush(
  382. ctx context.Context,
  383. req *types.Request,
  384. ) (*ReqRes, error) {
  385. reqres, err := cli.queueRequest(ctx, req, true)
  386. if err != nil {
  387. return nil, queueErr(err)
  388. }
  389. if err := cli.Flush(ctx); err != nil {
  390. return nil, err
  391. }
  392. return reqres, cli.Error()
  393. }
  394. func queueErr(e error) error {
  395. return fmt.Errorf("can't queue req: %w", e)
  396. }
  397. // drainQueue marks as complete and discards all remaining pending requests
  398. // from the queue.
  399. func (cli *socketClient) drainQueue(ctx context.Context) {
  400. cli.mtx.Lock()
  401. defer cli.mtx.Unlock()
  402. // mark all in-flight messages as resolved (they will get cli.Error())
  403. for req := cli.reqSent.Front(); req != nil; req = req.Next() {
  404. reqres := req.Value.(*ReqRes)
  405. reqres.SetDone()
  406. }
  407. // Mark all queued messages as resolved.
  408. //
  409. // TODO(creachadair): We can't simply range the channel, because it is never
  410. // closed, and the writer continues to add work.
  411. // See https://github.com/tendermint/tendermint/issues/6996.
  412. for {
  413. select {
  414. case <-ctx.Done():
  415. return
  416. case reqres := <-cli.reqQueue:
  417. reqres.SetDone()
  418. default:
  419. return
  420. }
  421. }
  422. }
  423. //----------------------------------------
  424. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  425. switch req.Value.(type) {
  426. case *types.Request_Echo:
  427. _, ok = res.Value.(*types.Response_Echo)
  428. case *types.Request_Flush:
  429. _, ok = res.Value.(*types.Response_Flush)
  430. case *types.Request_Info:
  431. _, ok = res.Value.(*types.Response_Info)
  432. case *types.Request_CheckTx:
  433. _, ok = res.Value.(*types.Response_CheckTx)
  434. case *types.Request_Commit:
  435. _, ok = res.Value.(*types.Response_Commit)
  436. case *types.Request_Query:
  437. _, ok = res.Value.(*types.Response_Query)
  438. case *types.Request_InitChain:
  439. _, ok = res.Value.(*types.Response_InitChain)
  440. case *types.Request_PrepareProposal:
  441. _, ok = res.Value.(*types.Response_PrepareProposal)
  442. case *types.Request_ExtendVote:
  443. _, ok = res.Value.(*types.Response_ExtendVote)
  444. case *types.Request_VerifyVoteExtension:
  445. _, ok = res.Value.(*types.Response_VerifyVoteExtension)
  446. case *types.Request_ApplySnapshotChunk:
  447. _, ok = res.Value.(*types.Response_ApplySnapshotChunk)
  448. case *types.Request_LoadSnapshotChunk:
  449. _, ok = res.Value.(*types.Response_LoadSnapshotChunk)
  450. case *types.Request_ListSnapshots:
  451. _, ok = res.Value.(*types.Response_ListSnapshots)
  452. case *types.Request_OfferSnapshot:
  453. _, ok = res.Value.(*types.Response_OfferSnapshot)
  454. case *types.Request_FinalizeBlock:
  455. _, ok = res.Value.(*types.Response_FinalizeBlock)
  456. }
  457. return ok
  458. }
  459. func (cli *socketClient) stopForError(err error) {
  460. if !cli.IsRunning() {
  461. return
  462. }
  463. cli.mtx.Lock()
  464. cli.err = err
  465. cli.mtx.Unlock()
  466. cli.logger.Info("Stopping abci.socketClient", "reason", err)
  467. cli.Stop()
  468. }